/**
 * @class ConfigEntry
 * @extends Entity
 * @property {number} id
 * @property {number} created_at
 * @property {number} updated_at
 * @property {string} key
 * @property {string} value
 * @property {string} description
 */
class ConfigEntry extends Entity {
    static _name = 'configentry';
    static _defaults = { key: '', value: '', description: '' };

    static _cache = null;       // cached result of all()
    static _cachePromise = null; // dedup concurrent all() calls

    static async _cachedAll() {
        if (this._cache) return this._cache;
        if (this._cachePromise) return this._cachePromise;
        this._cachePromise = this.all().then(entries => {
            this._cache = entries;
            this._cachePromise = null;
            return entries;
        });
        return this._cachePromise;
    }

    static _invalidateCache() { this._cache = null; }

    static async set(key, value) {
        const all = await this._cachedAll();
        let entry = all.find(e => e.key === key);
        if (entry) entry.value = value;
        else entry = new ConfigEntry({ key, value });
        const res = await entry.save();
        this._invalidateCache();
        return res;
    }

    /** @return Promise<?string> */
    static async get(key) {
        const all = await this._cachedAll();
        const entry = all.find(e => e.key === key);
        return entry ? entry.value : null;
    }
}
