
const Slack = require('./slack.js').Slack
    ,INACTIVE_DELAY = 120000

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();
    });
}, 60000);

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

SlackManager.prototype.lazyGet = function(sess, reqT) {
    var key = "SLACK_" +sess.sessId
        ,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(sess, 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;

