"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const util_1 = require("../../shared/preferences/util");
const Util_1 = require("../../shared/Util");
/** Static class with methods for saving, loading and parsing the Preferences file */
class AppPreferencesFile {
    /** Read the file, or create a new one using the defaults, and return the preferences */
    static async readOrCreate(onError) {
        let error, data;
        // Try to get the data from the file
        try {
            data = await AppPreferencesFile.readFile(onError);
        }
        catch (e) {
            error = e;
        }
        // If that failed, set data to default and save it to a new file
        if (error || !data) {
            data = Util_1.deepCopy(util_1.defaultPreferencesData);
            await AppPreferencesFile.saveFile(data)
                .catch(() => console.log('Failed to save default preferences file!'));
        }
        // Return
        return data;
    }
    static readFile(onError) {
        return new Promise((resolve, reject) => {
            Util_1.readJsonFile(AppPreferencesFile.filePath, AppPreferencesFile.fileEncoding)
                .then(json => resolve(AppPreferencesFile.parseData(json, util_1.defaultPreferencesData, onError)))
                .catch(reject);
        });
    }
    static saveFile(data) {
        return new Promise((resolve, reject) => {
            // Convert config to json string
            const json = AppPreferencesFile.stringifyData(data);
            // Save the config file
            fs.writeFile(AppPreferencesFile.filePath, json, function (error) {
                if (error) {
                    return reject(error);
                }
                else {
                    return resolve();
                }
            });
        });
    }
    static parseData(data, defaultData, onError) {
        // This makes sure that only the necessary properties are copied
        // And that the missing ones are set to their default value
        return util_1.overwritePreferenceData(Util_1.deepCopy(defaultData), data, onError);
    }
    static stringifyData(data) {
        return Util_1.stringifyJsonDataFile(data);
    }
}
/** Path to the preferences file */
AppPreferencesFile.filePath = './preferences.json';
/** Encoding used by preferences file */
AppPreferencesFile.fileEncoding = 'utf8';
exports.AppPreferencesFile = AppPreferencesFile;
//# sourceMappingURL=AppPreferencesFile.js.map