EXPORTED_SYMBOLS = ["module"];

var module = function (app, common) {

    var log = function(str, method) {
        common.log('[-common.timers]: ' + str, method);
    }

    var Cc = Components.classes["@mozilla.org/timer;1"];

    function Timer(ms, callback, scope) {
        this._callback = function() { callback.call(scope||null); };
        this._interval = 0;
        this.setInterval(ms);
    }

    Timer.prototype = {
        constructor: Timer,
        setInterval: function(v) {
            v = Number(v);
            if (this._interval != v) {
                this._interval = v;
                var started = this._timer;
                this.stop();
                if (started) {
                    this.start();
                }
            }
        },
        start: function() {
            if (!this._timer && (this._interval > 1)) {
                this._timer = thisModule.setInterval(this._callback, this._interval);
            }
        },
        stop: function() {
            if (this._timer) {
                this._timer.cancel();
                this._timer = null;
            }
        },
        finalize: function() {
            this.stop();
            this._callback = null;
            this._interval = 0;
        }
    };

    var timers = [];

    var thisModule = {
        setTimeout: function(func, ms, scope) {
            if (arguments.length > 2) {
                func = func.bind(scope);
            }
            var tmr = Cc.createInstance(Components.interfaces.nsITimer);
            tmr.initWithCallback(func, ms, Components.interfaces.nsITimer.TYPE_ONE_SHOT);
            return tmr;
        },
        setInterval: function(func, ms, scope) {
            if (arguments.length > 2) {
                func = func.bind(scope);
            }
            var tmr = Cc.createInstance(Components.interfaces.nsITimer);
            tmr.initWithCallback(func, ms, Components.interfaces.nsITimer.TYPE_REPEATING_PRECISE);
            return tmr;
        },
        create: function(ms, callback, scope) {
            if (typeof ms == 'function') {
                var old = scope;
                scope = callback;
                callback = ms;
                ms = 0;
            }
            var tmr = new Timer(ms, callback, scope);
            timers.push(tmr);
            return tmr;
        },
        stopAll: function() {
            for (var i=0; i<timers.length; ++i) {
                timers[i].stop();
            }
        },
        startAll: function() {
            for (var i=0; i<timers.length; ++i) {
                timers[i].start();
            }
        },
        finalize: function() {
            log('finalize');
            for (var i=0; i<timers.length; ++i) {
                timers[i].finalize();
            }
            timers = [];
        }
    };
    return thisModule;
};