/**
 * Timer.js
 *
 * A dojo-based Timer class
 */
dojo.provide("atemi.util.Timer");

dojo.declare("atemi.util.Timer", null, {
    /**
     * @param int delay The delay between timer events, in milliseconds
     * @param int repeatCount Specifies the number of repetitions. If zero, the timer repeats infinitely. If nonzero, the timer runs the specified number of times and then stops. 
     */
    constructor: function(delay, repeatCount) 
    {
        this.delay = delay;
        this.repeatCount = repeatCount;
        
        this.currentCount = 0;
    },


    /**
     * Stops the timer, if it is running, and sets the currentCount property back to 0, like the reset button of a stopwatch.
     */
    reset: function()
    {
        this.stop();
        this.currentCount = 0;
    },


    /**
     * Starts the timer, if it is not already running.
     */
    start: function()
    {
        // Sanity check: Ensure the timer hasn't run its course
        if (this.repeatCount == 0 || this.currentCount < this.repeatCount) {
            this.timerID = setTimeout(dojo.hitch(this, this._timeout), this.delay);
        }
    },


    /**
     * Stops the timer
     */
    stop: function()
    {
        clearTimeout(this.timerID);
        this.timerID = null;
    },


    _timeout: function()
    {
        this.currentCount++;
        this.timerDidFire();

        if (this.currentCount == this.repeatCount) {
            this.timerDidComplete();
        } else {
            this.start();
        }
    },


    /**
     * Method that's called when the timer fires.  
     * Interested listeners can connect to this method. 
     */
    timerDidFire: function()
    {
    },


    /**
     * Dispatched whenever it has completed the number of requests set by repeatCount
     */ 
    timerDidComplete: function()
    {
        this.stop();
    }
});

