"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonFileSettingsService = void 0;
const path = require("path");
const helpers_1 = require("../helpers");
const _ = require("lodash");
const yok_1 = require("../yok");
class JsonFileSettingsService {
    get lockFilePath() {
        return `${this.jsonSettingsFilePath}.lock`;
    }
    constructor(jsonFileSettingsPath, $fs, $lockService, $logger) {
        this.$fs = $fs;
        this.$lockService = $lockService;
        this.$logger = $logger;
        this.jsonSettingsFilePath = null;
        this.jsonSettingsData = null;
        this.jsonSettingsFilePath = jsonFileSettingsPath;
    }
    getSettingValue(settingName, cacheOpts) {
        return __awaiter(this, void 0, void 0, function* () {
            const action = () => __awaiter(this, void 0, void 0, function* () {
                yield this.loadUserSettingsFile();
                if (this.jsonSettingsData && _.has(this.jsonSettingsData, settingName)) {
                    const data = this.jsonSettingsData[settingName];
                    const dataToReturn = data.modifiedByCacheMechanism ? data.value : data;
                    if (cacheOpts && cacheOpts.cacheTimeout) {
                        if (!data.modifiedByCacheMechanism) {
                            return null;
                        }
                        const currentTime = Date.now();
                        if (currentTime - data.time > cacheOpts.cacheTimeout) {
                            return null;
                        }
                    }
                    return dataToReturn;
                }
                return null;
            });
            return this.$lockService.executeActionWithLock(action, this.lockFilePath);
        });
    }
    saveSetting(key, value, cacheOpts) {
        return __awaiter(this, void 0, void 0, function* () {
            const settingObject = {};
            settingObject[key] = value;
            return this.saveSettings(settingObject, cacheOpts);
        });
    }
    removeSetting(key) {
        return __awaiter(this, void 0, void 0, function* () {
            const action = () => __awaiter(this, void 0, void 0, function* () {
                yield this.loadUserSettingsFile();
                delete this.jsonSettingsData[key];
                yield this.saveSettings();
            });
            return this.$lockService.executeActionWithLock(action, this.lockFilePath);
        });
    }
    saveSettings(data, cacheOpts) {
        const action = () => __awaiter(this, void 0, void 0, function* () {
            yield this.loadUserSettingsFile();
            this.jsonSettingsData = this.jsonSettingsData || {};
            _(data)
                .keys()
                .each((propertyName) => {
                this.jsonSettingsData[propertyName] =
                    cacheOpts &&
                        cacheOpts.useCaching &&
                        !data[propertyName].modifiedByCacheMechanism
                        ? {
                            time: Date.now(),
                            value: data[propertyName],
                            modifiedByCacheMechanism: true,
                        }
                        : data[propertyName];
            });
            this.$fs.writeJson(this.jsonSettingsFilePath, this.jsonSettingsData);
        });
        return this.$lockService.executeActionWithLock(action, this.lockFilePath);
    }
    loadUserSettingsFile() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.jsonSettingsData) {
                yield this.loadUserSettingsData();
            }
        });
    }
    loadUserSettingsData() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.$fs.exists(this.jsonSettingsFilePath)) {
                const unexistingDirs = this.getUnexistingDirectories(this.jsonSettingsFilePath);
                this.$fs.writeFile(this.jsonSettingsFilePath, null);
                if (process.env.SUDO_USER) {
                    for (const dir of unexistingDirs) {
                        yield this.$fs.setCurrentUserAsOwner(dir, process.env.SUDO_USER);
                    }
                }
            }
            const data = this.$fs.readText(this.jsonSettingsFilePath);
            try {
                this.jsonSettingsData = (0, helpers_1.parseJson)(data);
            }
            catch (err) {
                this.$logger.trace(`Error while trying to parseJson ${data} data from ${this.jsonSettingsFilePath} file. Err is: ${err}`);
                this.$fs.deleteFile(this.jsonSettingsFilePath);
            }
        });
    }
    getUnexistingDirectories(filePath) {
        const unexistingDirs = [];
        let currentDir = path.join(filePath, "..");
        while (true) {
            if (this.$fs.exists(currentDir)) {
                break;
            }
            unexistingDirs.push(currentDir);
            currentDir = path.join(currentDir, "..");
        }
        return unexistingDirs;
    }
}
exports.JsonFileSettingsService = JsonFileSettingsService;
yok_1.injector.register("jsonFileSettingsService", JsonFileSettingsService, false);
