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

function ConfigModel() {
    DatabaseModel.call(this);
    this.key = "";
    this.value = "";
}

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

ConfigModel.prototype.getTableName = function() {
    return "config";
}

ConfigModel.prototype.createOrUpdateBase = async function(dbHelper) {
    await dbHelper.runSql(`CREATE TABLE IF NOT EXISTS 'config' (
        key STRING NOT NULL PRIMARY KEY,
        value STRING
        )`);
}

ConfigModel.prototype.describe = function() {
    return {
        "key": this.key,
        "value": this.value
    };
}

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

ConfigModel.prototype.fromDb = function(dbObj) {
    this.key = dbObj["key"];
    this.value = dbObj["value"];
}

class ConfigLoader
{
    #loading = null;
    #configEntries = {};

    constructor(app) {
        this.#loading = this.#init(app);
    }

    async #init(app) {
        // FIXME
    }

    async getValue(key) {
        await this.#loading;
        return this.#configEntries[key] || null;
    }

    async setValue(key, value) {
        await this.#loading;
        return this.#configEntries[key] = value;
    }

    async flush(app) {
        await this.#loading;
        // FIXME
    }
}

module.exports.ConfigModel = ConfigModel;
module.exports.ConfigLoader = (app) => new ConfigModel(app);

