"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Store = exports.SERVERSTATEDIRNAME = void 0;
const fs_1 = require("fs");
const promises_1 = require("fs/promises");
const path_1 = __importDefault(require("path"));
const atomicWrite_1 = require("../atomicWrite");
exports.SERVERSTATEDIRNAME = 'serverState';
class Store {
    filePath = '';
    fileName = '';
    initPromise = null;
    constructor(server, storePath, fileName = 'settings.json') {
        this.filePath = path_1.default.join(server.config.configPath, exports.SERVERSTATEDIRNAME, storePath);
        this.fileName = fileName;
        this.initPromise = this.init().catch((error) => {
            console.log(`Could not initialise ${path_1.default.join(this.filePath, this.fileName)}`);
            console.log(error);
        });
    }
    // Wait for initialization to complete before performing operations
    async waitForInit() {
        if (this.initPromise) {
            await this.initPromise;
        }
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    async read() {
        await this.waitForInit();
        const data = await (0, promises_1.readFile)(path_1.default.join(this.filePath, this.fileName), 'utf8');
        return JSON.parse(data);
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    async write(data) {
        await this.waitForInit();
        return (0, atomicWrite_1.atomicWriteFile)(path_1.default.join(this.filePath, this.fileName), JSON.stringify(data));
    }
    async init() {
        try {
            /* tslint:disable:no-bitwise */
            await (0, promises_1.access)(this.filePath, fs_1.constants.R_OK | fs_1.constants.W_OK);
            /* tslint:enable:no-bitwise */
        }
        catch (_error) {
            try {
                await (0, promises_1.mkdir)(this.filePath, { recursive: true });
            }
            catch (_error) {
                console.log(`Error: Unable to create ${this.filePath}`);
            }
        }
    }
}
exports.Store = Store;
//# sourceMappingURL=store.js.map