"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.disableCustomHtml = exports.customHtml = exports.customHtmlSections = void 0;
exports.watchLoadCustomHtml = watchLoadCustomHtml;
exports.getSection = getSection;
exports.getAllSections = getAllSections;
exports.saveCustomHtml = saveCustomHtml;
const misc_1 = require("./misc");
const watchLoad_1 = require("./watchLoad");
const config_1 = require("./config");
const promises_1 = require("fs/promises");
const plugins_1 = require("./plugins");
const lodash_1 = __importDefault(require("lodash"));
const FILE = 'custom.html';
exports.customHtmlSections = ['style', 'script', 'beforeHeader', 'afterHeader', 'afterMenuBar', 'afterList',
    'footer', 'top', 'bottom', 'afterEntryName', 'beforeLogin', 'unauthorized', 'htmlHead', 'userPanelAfterInfo'];
exports.customHtml = watchLoadCustomHtml();
exports.disableCustomHtml = (0, config_1.defineConfig)(misc_1.CFG.disable_custom_html, false);
function watchLoadCustomHtml(folder = '') {
    const sections = new Map();
    const res = (0, watchLoad_1.watchLoad)((0, misc_1.prefix)('', folder, '/') + FILE, data => {
        const re = /^\[([^\]]+)] *$/gm;
        sections.clear();
        if (!data)
            return;
        let name = 'top';
        do {
            let last = re.lastIndex;
            const match = re.exec(data);
            const content = data.slice(last, !match ? undefined : re.lastIndex - (match?.[0]?.length || 0)).trim();
            if (content)
                sections.set(name, content);
            name = match?.[1];
        } while (name);
    });
    return Object.assign(res, { sections });
}
function getSection(name) {
    return (!exports.disableCustomHtml.get() && exports.customHtml.sections.get(name) || '')
        + (0, plugins_1.mapPlugins)(pl => pl.getData().getCustomHtml()[name]).join('\n');
}
function getAllSections() {
    const keys = (0, plugins_1.mapPlugins)(pl => Object.keys(pl.getData().getCustomHtml()));
    keys.push(Array.from(exports.customHtml.sections.keys()));
    const all = lodash_1.default.uniq(keys.flat());
    return Object.fromEntries(all.map(x => [x, getSection(x)]));
}
async function saveCustomHtml(sections) {
    const text = Object.entries(sections).filter(([k, v]) => v?.trim()).map(([k, v]) => `[${k}]\n${v}\n\n`).join('');
    await (0, promises_1.writeFile)(FILE, text);
    exports.customHtml.sections.clear();
    for (const [k, v] of Object.entries(sections))
        if (v)
            exports.customHtml.sections.set(k, v);
}
