"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Storage = void 0;
const os = require("node:os");
const path = require("node:path");
const clone = require("clone");
const dot_prop_1 = require("dot-prop");
const fs = require("fs-extra");
const DATA_FOLDER = path.join(os.homedir(), '.wiz');
const DATA_FILE_PATH = path.join(DATA_FOLDER, 'config.json');
class Storage {
    static get() {
        return Storage.ensureFileExists()
            .then(() => getData());
    }
    static getSync() {
        Storage.ensureFileExistsSync();
        return fs.readJsonSync(DATA_FILE_PATH, { throws: false }) || {};
    }
    static set(newData) {
        return Storage.ensureFileExists()
            .then(() => getData())
            .then((oldData) => {
            const data = Object.assign(oldData, newData);
            return fs.outputJson(DATA_FILE_PATH, data);
        });
    }
    static clear() {
        return writeEmptyConfig();
    }
    static reset(fields) {
        return Storage.ensureFileExists()
            .then(() => fs.readJson(DATA_FILE_PATH))
            .then((config) => this.removeFields(config, fields))
            .then(({ modified, config }) => {
            if (modified) {
                return fs.outputJson(DATA_FILE_PATH, config);
            }
        });
    }
    static removeFields(obj, fields) {
        const config = clone(obj);
        const modified = fields
            .map((field) => (0, dot_prop_1.delete)(config, field))
            .some(Boolean);
        return { modified, config };
    }
    static ensureFileExists() {
        return fs.pathExists(DATA_FILE_PATH)
            .then((exists) => {
            if (!exists) {
                return writeEmptyConfig();
            }
        });
    }
    static ensureFileExistsSync() {
        const exists = fs.existsSync(DATA_FILE_PATH);
        if (!exists) {
            fs.outputJsonSync(DATA_FILE_PATH, {});
        }
    }
}
exports.Storage = Storage;
function writeEmptyConfig() {
    return fs.outputJson(DATA_FILE_PATH, {});
}
function getData() {
    return fs.readJson(DATA_FILE_PATH)
        .then((data) => {
        return data || {};
    })
        .catch(() => {
        return {};
    });
}
//# sourceMappingURL=index.js.map