/**
 * Timer service as per Timer XML description
 * This may be subclassed to provide functionality
 */
package service;

import xmltypes.*;

public class TickerTimer implements Timer {
    private Time time;
    private boolean isValid;
    private Ticker ticker;

    /**
     * Constructor with no starting time has
     * invalid timer and any time
     */
    public TickerTimer() {
	time = new Time("12:00:00");
	isValid = false;
	new Ticker(time).start();
    }

    public TickerTimer(Time t) {
	time = t;
	isValid = true;
	ticker = new Ticker(time);
	ticker.start();
    }
 
    public void setTime(Time t) {
	System.out.println("Setting time to " + t);
	time = t;
	isValid = true;
	if (ticker != null) {
	    ticker.stopRunning();
	}
	ticker = new Ticker(time);
	ticker.start();
    }

    public Time getTime() {
	return time;
    }

    public boolean isValidTime() {
	if (isValid) {
	    return true;
	} else {
	    return false;
	}
    }
}

class Ticker extends Thread {
    private Time time;
    private boolean keepRunning = true;

    public Ticker(Time t) {
	time = t;
    }

    public void run() {
	while (keepRunning) {
	    try {
		sleep(1000);
	    } catch(InterruptedException e) {
	    }
	    time.increment();
	}
    }

    public void stopRunning() {
	keepRunning = false;
    }
}
