import java.lang.*;

/**
  *A timer runs on an independent thread
  *It provides a registration facility so that objects can request
  *to receive "tick" messages on a regular cycle.
  */
class Timer extends Object implements Runnable{
	protected MovablePiece[] list;
	protected int ptr;
	protected BricklesView theView;
	protected Thread theThread;
	protected boolean running;

	/**
	  *The constructor initializes the timer's attributes
	  *The timer is initially stopped
	  */
	public Timer(BricklesView newView){
		theView = newView;
		list = new MovablePiece[5];
		ptr = -1;
		theThread = new Thread(this);
	}

	/**
	  *The timer is started by starting the thread
	  *pre:  the timer is idle but not stopped
	  *post: the timer is running
	  */
	public void start(){
		theThread.start();
	}

	/**
	  *MovablePieces use this method to register for timer "ticks"
	  */
	public void register(MovablePiece piece){
		ptr = ptr + 1;
		list[ptr] = piece;
	}

	/**
	  *This method is used to suspend the sending of "tick" messages
	  */
	public void pause(){
		running = false;
	}

	/**
	  *This method is used to resume the sending of "tick" messages
	  */
	public void resume(){
		running = true;
	}

	/**
	  *The main logic executed by the timer thread
	  */
	public void run(){
		running = true;
		for(;;){
			if((ptr > -1) && running){
				for(int i = 0; i<=ptr;i++){
					list[i].tick();
				}	
			}
			theView.repaint();
			try{
				theThread.sleep(75);
			}
			catch(InterruptedException e){}
		}
	}
}
