//# sourceURL=jobs/TickController.js
/**
 * $Id: Controller.js 279 2017-10-28 22:33:19Z patrick $
 */
/* globals define,Promise,TickController */

define( [ 'Controller', 'util' ], function( Controller, util ) {
    /**
     * TickController implements a time-based controller for entities.
     * An entity with a "delay" attribute will receive updates on that
     * interval (milliseconds).
     */

    TickController = function( source ) {
        Controller.call( this, source );
    };

    TickController.prototype = Object.create(Controller.prototype);
    TickController.prototype.constructor = TickController;
    
    /** 
     * Override of Controller's default implementation (which does nothing).
     * Stop any running timer cycle and run immediately to start a new
     * timer cycle (in case the new Entity needs service sooner than the
     * current running interval would allow. 
     * @param {Entity} ent - The new entity just created.
     */
    TickController.prototype.finalizeEntity = function( ent ) {
        var self = this;
        return new Promise( function( resolve, reject ) {
            self.stop(); /* stop any running timer */
            self.run();
            resolve( self );
        });
    };
    
    TickController.prototype.start = function() {
        var self = this;
        return new Promise( function( resolve, reject ) {
            self.run();
            resolve( self );
        });
    };
    
    TickController.prototype.run = function() {
        /* Delay until our next entity needs us */
        var now = new Date().getTime(),
            minTick = now + 60000;
        for( var key in this.entities ) {
            if ( this.entities.hasOwnProperty(key) ) {
                var nextTick = this.entities[key].getAttribute("__nextTick", 0);
                if ( nextTick <= now ) {
                    /* Figure out next tick time. Setting it on Entity causes notify */
                    var delay = this.entities[key].getAttribute("delay", 1000);
                    nextTick = now + delay;
                    this.entities[key].setAttribute("__nextTick", nextTick);
                }
                if ( nextTick < minTick ) {
                    minTick = nextTick;
                }
            }
        }
        var delay = now - minTick;
        if ( delay < 0 ) { delay = 10; }
        this.startDelay( delay );
    };
  
    return TickController;

}); // define
