package app;


import java.util.*;
import java.awt.event.*;
import javax.swing.*;

import app.AbstractMultimediaApp;
import event.*;


/**
 * A simple MultimediaApp that uses a Metronome
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class      StopWatchApp
       extends    AbstractMultimediaApp
       implements ActionListener, MetronomeListener
{
    private boolean                   running;
    private JLabel                    label;       
    private Metronome                 metronome;
    
    private static final String       START = "Start";
    private static final String       STOP  = "Stop";


    /**
     * Handle actionPerformed messages
     * (required by ActionListener)
     *
     * @param event  The ActionEvent that generated the message
     */
    public void actionPerformed(ActionEvent event)
    {
       String   actionCommand;
       
       actionCommand = event.getActionCommand();
       if      (actionCommand.equals(START))
       {
          label.setText("0");          
          metronome.reset();          
          metronome.start();
          running = true;          
       }
       else if (actionCommand.equals(STOP))
       {
          metronome.stop();
          running = false;          
       }
    }
    

    /**
     * Respond to handleTick messages
     * (required by MetronomeListener)
     *
     * @param millis   The time
     */
    public void handleTick(int millis)
    {
       label.setText(""+millis/1000);       
    }
    

    /**
     * Called to indicate that this MultimediaApp has been loaded
     */
    public void init()
    {
       JButton                   start, stop;       
       JPanel                    contentPane;       
              
       running = false;
       
       contentPane = (JPanel)rootPaneContainer.getContentPane();   
       contentPane.setLayout(null);
       
       label       = new JLabel("0");
       label.setBounds(250,100,100,100);       
       contentPane.add(label);    

       start = new JButton(START);
       start.setBounds(50,300,100,50);
       start.addActionListener(this);
       contentPane.add(start);
       

       stop  = new JButton(STOP);
       stop.setBounds(450,300,100,50);
       stop.addActionListener(this);
       contentPane.add(stop);
       

       metronome = new Metronome(1000, true);
       metronome.addListener(this);
    }
    

    /**
     * Called to indicate that this MultimediaApp should start
     * (required by MultimediaApp)
     */
    public void start()
    {
       if (running) metronome.start();
    }
    

    /**
     * Called to indicate that this MultimediaApp should stop
     * (required by MultimediaApp)
     */
    public void stop()
    {
       if (running) metronome.stop();
    }
}
