"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var debug = require("debug");
var fs = require("fs-extra");
var SchemaUpdater_1 = require("./SchemaUpdater");
var ConfigurationPersistence = (function () {
    function ConfigurationPersistence() {
        this.configFile = SchemaUpdater_1.SchemaUpdater.updateToVersion1();
        this.debug = debug('ConfigurationPersistence');
        if (typeof global._ConfigurationPersistence === 'undefined') {
            global._ConfigurationPersistence = this.readFromFile();
        }
        this.debug('Init ConfigurationPersistence');
    }
    ConfigurationPersistence.prototype.delete = function (name) {
        this.debug('Deleting %s', name);
        delete global._ConfigurationPersistence[name];
        return true;
    };
    ConfigurationPersistence.prototype.save = function (name, value) {
        this.debug('Saving %s with value "%o"', name, value);
        global._ConfigurationPersistence[name] = value;
        return true;
    };
    ConfigurationPersistence.prototype.restore = function (name, defaultValue) {
        this.debug('Restoring %s', name);
        var value = global._ConfigurationPersistence[name];
        return typeof value !== 'undefined' ? value : defaultValue;
    };
    ConfigurationPersistence.prototype.persistToFile = function () {
        this.debug('Saving configuration to persistent storage: %o', global._ConfigurationPersistence);
        try {
            return fs.writeJsonSync(this.configFile, global._ConfigurationPersistence, { spaces: 2 });
        }
        catch (error) {
            this.debug('An error occurred while persisting the configuration: %s', error);
        }
    };
    ConfigurationPersistence.prototype.readFromFile = function () {
        this.debug("Reading config file \"" + this.configFile + "\"...");
        try {
            return fs.readJSONSync(this.configFile);
        }
        catch (error) {
            var schemataKeys = Object.keys(SchemaUpdater_1.SchemaUpdater.SCHEMATA);
            return SchemaUpdater_1.SchemaUpdater.SCHEMATA[schemataKeys[schemataKeys.length - 1]];
        }
    };
    return ConfigurationPersistence;
}());
var settings = new ConfigurationPersistence();
exports.settings = settings;
//# sourceMappingURL=ConfigurationPersistence.js.map