
const Slack = require('./slack.js').Slack
    ,MultiChatManager = require('./multichatManager.js').MultiChatManager
    ,INACTIVE_DELAY = 120000
    ,PING_DELAY = 600000
    ,RTM_PING_DELAY = 15000
;

function SlackManager() {
    this.cache = require('memory-cache');
}

var instance = new SlackManager();

setInterval(function() {
    var keys = instance.cache.keys();
    keys.forEach(function(instKey) {
        instance.cache.get(instKey).ping();
    });
}, PING_DELAY);

setInterval(function() {
    var keys = instance.cache.keys(),
        now = Date.now();
    keys.forEach(function(instKey) {
        var inst = instance.cache.get(instKey);
        if (inst.data.cleanTyping(now))
            MultiChatManager.onCtxUpdated(inst);
    });
}, 1000);

SlackManager.prototype.getAuthScope = function() {
    return [
        "identity.basic",
        "identity.email"
    ];
};
setInterval(function() {
    var keys = instance.cache.keys();
    keys.forEach(function(instKey) {
        instance.cache.get(instKey).rtmPing();
    });
}, RTM_PING_DELAY);

SlackManager.prototype.getScope = function() {
    return [
        "client"
    ];
};

SlackManager.prototype.lazyGet = function(servId, slackToken, reqT) {
    var key = "SLACK_" +servId,
        val = this.cache.get(key);
    if (val) {
        this.cache.put(key, val, INACTIVE_DELAY, function(key, val) {
            instance.removed(key, val);
        });
    } else {
        val = new Slack(slackToken, this);
        this.cache.put(key, val, INACTIVE_DELAY, function(key, val) {
            instance.removed(key, val);
            val.close();
        });
    }
    return val;
};

SlackManager.prototype.removed = function(key, slack) {
    slack.close();
};

SlackManager.prototype.suicide = function(slack) {
    this.cache.del("SLACK_" +slack.sessId);
};

module.exports.SlackManager = instance;

