"use strict";
// This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const apiMiddleware_1 = require("./apiMiddleware");
const lodash_1 = __importDefault(require("lodash"));
const fast_glob_1 = __importDefault(require("fast-glob"));
const promises_1 = require("fs/promises");
const const_1 = require("./const");
const misc_1 = require("./misc");
const lang_1 = require("./lang");
const embedded_1 = __importDefault(require("./langs/embedded"));
const SendList_1 = require("./SendList");
const apis = {
    get_langs() {
        return new SendList_1.SendListReadable({
            doAtStart: async (list) => {
                for await (let name of fast_glob_1.default.stream((0, lang_1.code2file)('*'))) {
                    name = String(name);
                    const code = (0, lang_1.file2code)(name);
                    try {
                        const data = JSON.parse(await (0, promises_1.readFile)(name, 'utf8'));
                        list.add({ code, ...lodash_1.default.omit(data, 'translate') });
                    }
                    catch { }
                }
                for (const [code, data] of Object.entries(embedded_1.default))
                    list.add({ code, embedded: true, ...lodash_1.default.omit(data, 'translate') });
                list.close();
            }
        });
    },
    async del_lang({ code }) {
        validateCode(code);
        try {
            await (0, promises_1.rm)((0, lang_1.code2file)(code));
            return {};
        }
        catch (e) {
            return new apiMiddleware_1.ApiError(const_1.HTTP_SERVER_ERROR, e);
        }
    },
    async add_langs({ langs }) {
        (0, misc_1.apiAssertTypes)({ object: { langs } });
        for (let [code, content] of Object.entries(langs)) {
            code = (0, lang_1.file2code)(code);
            validateCode(code);
            const fn = (0, lang_1.code2file)(code);
            const s = content = String(content);
            if (!(0, misc_1.tryJson)(s))
                return new apiMiddleware_1.ApiError(const_1.HTTP_NOT_ACCEPTABLE, "bad content for file " + fn);
            await (0, promises_1.writeFile)(fn, s, 'utf8');
        }
        return {};
    }
};
exports.default = apis;
function validateCode(code) {
    if (!/^(\w\w)(-\w\w)*$/.test(code))
        throw new apiMiddleware_1.ApiError(const_1.HTTP_BAD_REQUEST, 'bad code/filename');
}
