/**
 * 
         -------- Copyright (C) [2012]  [Kristofer SCHWEIGER & Niklas FLORIAN1]---------

    This program is free software; you can redistribute it and/or modify it under the terms of the
 *  GNU General Public License as published by the Free Software Foundation; either version 2 of the License,
 *  or (at your option) any later version.
    This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *  See the GNU General Public License for more details.
 * 
    You should have received a copy of the GNU General Public License along with this program; if not, 
 *  write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA

 * 
 * For any licensing issues please contact us under following adress: Mosaik.Projekt.2012@gmail.com
 */

package util;

import util.simpleIO.Out;

public class TimerInitializer extends Thread {

	private final Timer timer;
	public final int speed;
	private boolean initFinished = false;
	
	/**
	 * Using the timer: Example
	 */
	public static void main(String[] args) {
		System.out.println("--- start ---");
		// speed: -2...ultra (10++ sec), -1...slow (4++ sec) 0...normal (1+ sec), 1...fast (0.5+ sec), 2...very fast (0.25+ sec)
		TimerInitializer ti = new TimerInitializer(-2);
		System.out.println("--- mid ---");
		while(!ti.initFinished()){
			Tools.sleep(333); Out.p(".");
		}
			
		ti.getNewTimer();
		System.out.println("--- finished ---");
		System.out.println("Total time: "+ti.timer.getTimeSec()+" seconds");
	}
	
	/**
	 * Simple constructor
	 * Standard speed and size.
	 */
	public TimerInitializer(){
		this(0);
	}
	
	/**
	 * Full constructor
	 * @param speed: -2...ultra (10++ sec), -1...slow (4++ sec) 0...normal (1+ sec), 1...fast (0.5+ sec), 2...very fast (0.25+ sec)
	 */
	public TimerInitializer(int speed){
		this.timer = new Timer();
		this.speed = speed;
		
		this.setDaemon(true);
		this.start();
	}
	
	public void run(){
		initTimer();
	}
	
	/**
	 * Initialize timer in thread.
	 */
	private synchronized void initTimer(){
		timer.INIT(speed);
		initFinished = true;
		this.notifyAll();
	}
	
	/**
	 * @return see full function
	 */
	public synchronized Timer getNewTimer(){
		return getNewTimer(0);
	}
	/**
	 * Generates new timers after first initialization is finished.
	 * Results in wait if initialization is still in progress.
	 * 
	 * @return a new timer with full compensation configuration.
	 */
	public synchronized Timer getNewTimer(int initialStorageSize){
		
		while(!initFinished){
			try{
				this.wait();
			}
			catch(InterruptedException e){}
		}
		
		Timer timer2 = new Timer(initialStorageSize);
		timer2.INIT_COPY(timer);
		return timer2;
	}
	
	/**
	 * @return true if the timer initialization is finished and get method can be used without wait.
	 */
	public boolean initFinished(){
		return initFinished;
	}

}
