(function() {
    // 定义15分钟的毫秒数
    var INACTIVITY_LIMIT = 15 * 60 * 1000;
    var inactivityTimer;

    var STORAGE_KEY = "lastActiveTime";
    var PAUSE_KEY = "activityPaused";

    var paused = false;

    function resetTimer() {
        // console.log('resetTimer: clearTimeout', inactivityTimer)
        clearTimeout(inactivityTimer);
        if (!paused) {
            // console.log('resetTimer: setTimeout', INACTIVITY_LIMIT)
            inactivityTimer = setTimeout(Steedos.logout, INACTIVITY_LIMIT);
        }
    }

    function updateActivity() {
        if (!paused) {
            localStorage.setItem(STORAGE_KEY, Date.now().toString());
            resetTimer();
        }
    }

    var events = [
        'mousemove',
        'mousedown',
        'keypress',
        'touchstart',
        'scroll',
        'click'
    ];
    events.forEach(function(event) {
        document.addEventListener(event, updateActivity, false);
    });

    window.addEventListener("storage", function(e) {
        if (e.key === STORAGE_KEY) {
            resetTimer();
        }
        if (e.key === PAUSE_KEY) {
            paused = e.newValue === "true";
            if (paused) {
                clearTimeout(inactivityTimer);
            } else {
                resetTimer();
            }
        }
    });

    window.SteedosLogoutMonitor = {
        pause: function() {
            localStorage.setItem(PAUSE_KEY, "true");
            paused = true;
            clearTimeout(inactivityTimer);
        },
        resume: function() {
            localStorage.setItem(PAUSE_KEY, "false");
            paused = false;
            updateActivity();
        }
    };

    (function init() {
        localStorage.setItem(PAUSE_KEY, "false");
        paused = false;
        updateActivity();
    })();
})();
