"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StorageHelper = exports.STORE_BACKUP_PREFIX = void 0;
const jsonfile_1 = require("jsonfile");
const app_1 = require("../config/app");
const logger_1 = require("./logger");
const utils = __importStar(require("./utils"));
const merge_1 = require("merge");
const archiver_1 = __importDefault(require("archiver"));
const fs_1 = require("fs");
const fs_extra_1 = require("fs-extra");
const logger = (0, logger_1.module)('Store');
exports.STORE_BACKUP_PREFIX = 'store-backup_';
/**
Constructor
**/
class StorageHelper {
    _store;
    config;
    get store() {
        return this._store;
    }
    constructor() {
        this._store = {};
    }
    async init(config) {
        this.config = config;
        for (const model in config) {
            const res = await this._getFile(config[model]);
            this._store[res.file] = res.data;
        }
        return this._store;
    }
    async backup(res) {
        const backupFile = `${exports.STORE_BACKUP_PREFIX}${utils.fileDate()}.zip`;
        await (0, fs_extra_1.mkdirp)(app_1.storeBackupsDir);
        const fileStream = (0, fs_1.createWriteStream)(utils.joinPath(app_1.storeBackupsDir, backupFile));
        return new Promise((resolve, reject) => {
            const archive = (0, archiver_1.default)('zip');
            archive.on('error', (err) => {
                reject(err);
            });
            // on stream closed we can end the request
            archive.on('end', () => {
                resolve(backupFile);
            });
            if (res) {
                res.set({
                    'Content-Type': 'application/json',
                    'Content-Disposition': `attachment; filename="${backupFile}"`,
                });
                archive.pipe(res);
            }
            archive.pipe(fileStream);
            // backup zwavejs files too
            archive.glob('*.jsonl', {
                cwd: app_1.storeDir,
            });
            for (const model in this.config) {
                const config = this.config[model];
                const filePath = utils.joinPath(app_1.storeDir, config.file);
                if ((0, fs_extra_1.existsSync)(filePath)) {
                    archive.file(filePath, {
                        name: config.file,
                    });
                }
            }
            void archive.finalize();
        });
    }
    async _getFile(config) {
        let err;
        let data;
        try {
            data = await (0, jsonfile_1.readFile)(utils.joinPath(app_1.storeDir, config.file));
        }
        catch (error) {
            err = error;
        }
        // ignore ENOENT error
        if (err) {
            if (err.code !== 'ENOENT') {
                logger.error('Error reading file: ' + config.file, err);
            }
            else {
                logger.warn(`${config.file} not found`);
            }
        }
        // replace data with default
        if (!data) {
            data = config.default;
        }
        else {
            data = Array.isArray(data) ? data : (0, merge_1.recursive)(config.default, data);
        }
        return { file: config.file, data: data };
    }
    get(model) {
        if (this._store[model.file]) {
            return this._store[model.file];
        }
        else {
            throw Error('Requested file not present in store: ' + model.file);
        }
    }
    async put(model, data) {
        await (0, jsonfile_1.writeFile)(utils.joinPath(app_1.storeDir, model.file), data);
        this._store[model.file] = data;
        return data;
    }
}
exports.StorageHelper = StorageHelper;
exports.default = new StorageHelper();
