
const crypto = require('crypto');
const MD5 = require('craftlabhttpserver/src/md5sum.js').string;
const { AccessModel, ACCESS_TO, ACCESS_TYPE } = require('../model/access.js');

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, linkLabel) {
    Access.call(this);
    this.linkId = linkId;
    this.linkLabel = linkLabel;
}
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: async (app, accessList) => {
                    if (accessList.isAdmin_)
                        return true;
                    return ((await app.databaseHelper.fetch(AccessModel, { accessTo: ACCESS_TO.admin, type: ACCESS_TYPE.everyOne })) || []).length > 0;
                },
                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, linkLabel) => {
    let session = module.exports.getSessionObj(req.cookies);
    if (!session)
        return;
    let accessItem = new LinkAccess(linkId, linkLabel);
    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;
}

