const crypto = require('crypto')
    ,Cache = require('../lib/node-file-cache.js');

function SessionManager() {
    this.sessions = Cache.create({
        file: "sessions.json"
    });
}

const DEFAULT_TTL = 60 * 60 * 24; // keep sessions 24h

function Session(reqT, sessId) {
    this.sessId = sessId;
    this.accountId = null;
    this.modifiedAt = reqT;
    this.isNative = false;
}

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) {
        var sess = new Session()
            ,cachedSession = this.sessions.get(request.cookies.sessID);
        sess.sessId = request.cookies.sessID;
        for (var i in cachedSession)
            if (cachedSession.hasOwnProperty(i))
                sess[i] = cachedSession[i];
        return sess;
    }
    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.closeSession = function(req) {
    if (req.account && req.session) {
        let sessionCountForUser = 0,
            allSessions = this.sessions.values();

        allSessions.forEach((sess) => {
            if (sess["accountId"] === req.account.id) {
                sessionCountForUser++;
                if (sess.sessId === req.session.sessId) {
                    this.sessions.expire(sess.sessId);
                }
            }
        });
        if (sessionCountForUser === 1) {
            // FIXME this session was the only one for this user, terminate all its connections (not linked in another logged account)
        }
    }
};

SessionManager.prototype.saveSession = function(session) {
    if (session) {
        var sessionData = {};
        for (var i in session)
            if (session.hasOwnProperty(i))
                sessionData[i] = session[i];
        this.sessions.set(session.sessId, sessionData, {
            life: DEFAULT_TTL
        });
    }
};

Session.prototype.setAccountId = function(reqT, accountId) {
    this.accountId = accountId;
    this.modifiedAt = reqT;
};

var sessMan = new SessionManager();

module.exports.SessionManager = sessMan;

