package stopwatch;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;	
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * Adds a KeyListener to the component provided in the constructor, 
 * which listens for the enter key and the space key. On receiving
 * either one, remembers that it has been pressed until the next
 * interrogation. Modified from an original version by Scott
 * Knight.
 * 
 * @author Greg Phillips
 * @version 7 February 2006
 *
 */
public class TimerKeys {
	
	protected boolean enterKey = false;
	protected boolean spaceKey = false;

	/**
	 * Adds a KeyListener to the provided <code>TimeDisplay</code>,
	 * which affects the values returned by <code>getEnter()</code> 
	 * and <code>getSpace()</code>.
	 * 
	 * @see #getEnter()
	 * @see #getSpace()
	 * 
	 * @param timeDisplay the timeDisplay to which the key listener
	 * should be added
	 */
	public TimerKeys(TimeDisplay timeDisplay) {
		timeDisplay.addKeyListener(new TimerKeyAdapter());
	}

	/**
	 * @return true if the enter key has been pressed since the
	 * last interrogation, false otherwise
	 */
	public boolean getEnter() {
		if (enterKey) {
			enterKey = false;
			return true;
		}
		return false;
	}

	/**
	 * @return true if the space bar has been pressed since the
	 * last interrogation, false otherwise
	 */
	public boolean getSpace() {
		if (spaceKey) {
			spaceKey = false;
			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		TimeDisplay newDisplay = new TimeDisplay();
		// ensure the application closes when the window closes
		newDisplay.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		TimerKeys timerKeys = new TimerKeys(newDisplay);
		while (true) {
			if (timerKeys.getSpace()) {
				System.out.println("Space bar was pressed");
			}
			if (timerKeys.getEnter()) {
				System.out.println("Enter key was pressed");
			}
			// Sleep for 10 milliseconds so our busy-wait
			// loop doesn't hog the entire CPU.
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// Something went badly wrong... bail.
				System.exit(0);
			}
		}
	}

	/**
	 * If the enter or space key is pressed, set an appropriate
	 * boolean variable in the enclosing class's scope. Modified
	 * from an original version by Scott Knight.
	 * 
	 * @author Greg Phillips
	 * @version 7 February 2006
	 */
	class TimerKeyAdapter extends KeyAdapter {
		public void keyPressed(KeyEvent e) {
			if (e.getKeyCode() == KeyEvent.VK_SPACE) {
				spaceKey = true;
				return;
			} else if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				enterKey = true;
				return;
			}
			return;
		}
	}
}

