const crypto = require('crypto')
    ,Cache = require('node-file-cache');

function SessionManager() {
    this.sessions = Cache.create();
}

SessionManager.defaultTtl = 60 * 60 * 24; // keep sessions 24h

function Session(reqT, sessId) {
    this.sessId = sessId;
    this.slackToken = null;
    this.modifiedAt = reqT;
}

SessionManager.createSessionId = function(req) {
    var token = Date.now() + "" +Math.random();
    return crypto.createHash('md5').update(token).digest('hex');
};

SessionManager.prototype.forRequest = function(request) {
    if (request.cookies && request.cookies.sessID) {
        return this.sessions.get(request.cookies.sessID);
    }
    return null;
};

SessionManager.prototype.lazyForRequest = function(request) {
    var session = this.forRequest(request);
    if (session) {
        return session;
    }
    var sessionId = SessionManager.createSessionId(request);
    session = new Session(request.reqT, sessionId);
    return session;
};

SessionManager.prototype.saveSession = function(session) {
    if (session) {
        this.sessions.set(session.sessId, session, {
            life: SessionManager.defaultTtl
        });
    }
};

Session.prototype.setSlackToken = function(reqT, slackToken) {
    this.slackUserId = slackToken["user_id"];
    this.slackTeamName = slackToken["team_name"];
    this.slackTeamId = slackToken["team_name"];
    this.slackToken = slackToken["access_token"];
    this.modifiedAt = reqT;
};

var sessMan = new SessionManager();

module.exports.SessionManager = sessMan;

