
const crypto = require('crypto');
const MD5 = require('craftlabhttpserver/src/md5sum.js').string;

module.exports = require('craftlabhttpserver/src/security.js');

function getAccessList(cookieObject) {
    let session = module.exports.getSessionObj(cookieObject);
    if (!session)
        return null;
    return session.accessList;
}

function Access() {
    this.dbId = "";
}
Access.prototype.id = function() { return ""; }

function LinkAccess(linkId) {
    Access.call(this);
    this.linkId = linkId;
}
LinkAccess.prototype = Object.create(Access.prototype);
LinkAccess.prototype.id = function() { return "LINK_"+this.linkId; }

module.exports.getAccessList = getAccessList;
module.exports.createSession = req => {
    const now = Date.now();
    let sessionInfos = {
        loginDateTime: now,
        expire: now + module.exports.SESSION_TIME,
        random: Math.random(),
        userAgent: req.headers['user-agent'],
        ipAddress: module.exports.getRequestIp(req),
        data: {
            accessList: {
                isAdmin: false
            }
        }
    };
    let sessionKey = MD5(JSON.stringify(sessionInfos));
    sessionInfos.sessionId = sessionKey;
    module.exports.pushSession(sessionKey, sessionInfos);
    req.cookies[module.exports.SESSION_COOKIE] = sessionKey;
    return { key: sessionKey, data: sessionInfos.data };
};
module.exports.setAdmin = (req, val) => {
    let session = module.exports.getSessionObj(req.cookies);
    if (!session)
        return;
    session.accessList.isAdmin = val;
    return session.accessList;
};
module.exports.addLinkToSession = (req, dbId, linkId) => {
    let session = module.exports.getSessionObj(req.cookies);
    if (!session)
        return;
    let accessItem = new LinkAccess(linkId);
    accessItem.dbId = dbId;
    session.accessList[accessItem.id()] = accessItem;
    return session.accessList;
};
module.exports.removeFromSession = (req, accessId) => {
    let session = module.exports.getSessionObj(req.cookies);
    if (!session)
        return;
    delete session.accessList[accessId];
    return session.accessList;
};

module.exports.setAdminFlat = () => {
    session.accessList.isAdmin = true;
}

