package jrummikub.control;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

import jrummikub.util.Event;
import jrummikub.util.IEvent;
import jrummikub.view.IView;

/**
 * Count-down timer used to limit the turn time
 */
public class TurnTimer implements ActionListener, ITurnTimer {
	private IView view;
	private int timeLeft = 60;
	private Timer timer;
	private Event timeRunOutEvent = new Event();

	/**
	 * Create a new timer using a given view to display the current time left
	 * 
	 * @param view
	 *            view to display
	 */
	public TurnTimer(IView view) {
		this.view = view;
		timer = new Timer(1000, this);
		timer.setRepeats(true);
		timer.setCoalesce(false);
		view.getPlayerPanel().setTimeLeft(timeLeft);
	}

	@Override
	public void startTimer() {
		timer.start();
	}

	@Override
	public void stopTimer() {
		timer.stop();
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		timeLeft--;
		view.getPlayerPanel().setTimeLeft(timeLeft);
		if (timeLeft == 0) {
			timer.stop();
			timeRunOutEvent.emit();
		}
	}

	@Override
	public IEvent getTimeRunOutEvent() {
		return timeRunOutEvent;
	}
}
