"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderPageInit = exports.find_language_suffixed_files = exports.template_resolution = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const config_1 = require("./config");
function template_resolution(base_path, sub_path, default_language) {
    return async (filename, language) => {
        if (!language)
            language = default_language;
        filename = await find_language_suffixed_files(path_1.default.join(base_path, sub_path, filename), language, default_language, ".html");
        return path_1.default.relative(base_path, filename);
    };
}
exports.template_resolution = template_resolution;
async function find_language_suffixed_files(filename, language, default_language = "en", overwrite_extension) {
    let ext_name = path_1.default.extname(filename);
    let basename = ext_name.length > 0 ? filename.slice(0, -ext_name.length) : filename;
    if (basename.endsWith("."))
        basename = basename.slice(0, -1);
    if (overwrite_extension)
        ext_name = overwrite_extension;
    if (!ext_name.startsWith("."))
        ext_name = "." + ext_name;
    const possible_filenames = [
        basename + "_" + language + ext_name,
        basename + "_" + default_language + ext_name,
        basename + ext_name,
    ];
    for (const filename of possible_filenames) {
        if (fs_1.default.existsSync(filename)) {
            return filename;
        }
    }
    throw new Error("Could not find file " + filename);
}
exports.find_language_suffixed_files = find_language_suffixed_files;
function renderPageInit(content_path, default_language) {
    const page_resolution = template_resolution(content_path + "/templates", "pages", default_language);
    return async function renderPage(page, language, res, user, properties) {
        const isLoggedIn = user !== undefined;
        // if page starts with / remove it
        if (page.startsWith("/"))
            page = page.slice(1);
        try {
            const page_template = await page_resolution(page, language);
            res.render(page_template, {
                language,
                page,
                isLoggedIn,
                user,
                CWIDE_STANDALONE_URL: config_1.config.CWIDE_STANDALONE_URL,
                ...properties,
            });
        }
        catch (e) {
            const page_template = await page_resolution("404", language);
            res.status(404);
            res.render(page_template, { language, page, isLoggedIn, user });
        }
    };
}
exports.renderPageInit = renderPageInit;
//# sourceMappingURL=utils.js.map