
const DatabaseModel = require("./DatabaseModel.js").DatabaseModel;

function SessionModel(sessionInfos) {
    DatabaseModel.call(this);
    this.userAgent = sessionInfos?.userAgent || "";
    this.ipAddress = sessionInfos?.ipAddress || "";
    this.loginDateTime = new Date(sessionInfos?.loginDateTime || 0);
    this.username = sessionInfos?.username || "";
    this.sessionId = sessionInfos?.sessionId || "";
    this.instance = sessionInfos?.instance || "";
}

SessionModel.prototype = Object.create(DatabaseModel.prototype);

SessionModel.prototype.getTableName = function() {
    return "session";
}

SessionModel.prototype.createOrUpdateBase = async function(dbHelper) {
    await dbHelper.runSql(`CREATE TABLE IF NOT EXISTS 'session' (
        sessionId STRING NOT NULL,
        instance string NOT NULL,
        useragent STRING NOT NULL,
        remoteAddress STRING NOT NULL,
        loginDateTime TIMESTAMP NOT NULL,
        username STRING NOT NULL,
        PRIMARY KEY (sessionId, instance))`);
}

SessionModel.prototype.describe = function() {
    return {
        "sessionId": this.sessionId,
        "useragent": this.userAgent,
        "remoteAddress": this.ipAddress,
        "loginDateTime": this.loginDateTime.getTime(),
        "username": this.username,
        "instance": this.instance
    };
}

SessionModel.prototype.versionColumn = function() { return "loginDateTime"; }

SessionModel.prototype.fromDb = function(dbObj) {
    this.sessionId = dbObj["sessionId"];
    this.userAgent = dbObj["useragent"];
    this.ipAddress = dbObj["remoteAddress"];
    this.loginDateTime.setTime(dbObj["loginDateTime"]);
    this.username = dbObj["username"];
    this.instance = dbObj["instance"];
}

module.exports.SessionModel = SessionModel;

