EXPORTED_SYMBOLS = ["module"];

var module = function (app, common) {
    function log(str) {
        app.log('[AuthObserver]: ' + str);
    }

    var LOGOUT_URL_REGEX = /^https?:\/\/([0-9a-z_-]+\.)?mail\.ru\/(cgi-bin\/logout|logout\.p?html)/i;
    var LOGIN_URL_REGEX = /^https?:\/\/(auth\.mail\.ru\/cgi-bin\/auth|love\.mail\.ru\/ajax\/login\.phtml\?.*Login)/i;
    var INTERVAL = 1200;

    var started = null;
    var timer = null;
    var timerFunc = function() {
        //log("timer!!");
        r._callback(true);
        timer = null;
    }
    var observer = function(topic, data, subject) {
        subject.QueryInterface(Components.interfaces.nsIHttpChannel);
        let url = subject.URI.spec;
        if (LOGOUT_URL_REGEX.test(url)) {
            log('LOGOUT_URL_REGEX.test(url) ' + url);
            if (timer) {
                timer.cancel();
                timer = null;
            }
            this._callback(false);
        } else {
            if (!timer && LOGIN_URL_REGEX.test(url)) {
                log('LOGIN_URL_REGEX.test(url) ' + url);
                timer = common.timers.setTimeout(timerFunc, INTERVAL);
                //log("timer created");
            }
        }
    };

    var r = {
        _callback: function () {},
        init: function (callback) {
            this._callback = callback;
            this.start();
        },
        start: function() {
            if (!started) {
                started = common.observerService.addObserver('http-on-modify-request', observer, this);
            }
        },
        finalize: function() {
            if (started) {
                common.observerService.removeObserver(started);
                started = null;
            }
        }
    };
    return r;
};