"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkAndFixSidebarPure = exports.checkAndFixSidebar = exports.addExerciseToSidebar = exports.generateSidebar = void 0;
const path = require("path");
const console_1 = require("./console");
const fs = require("fs");
const session_1 = require("../managers/session");
const rigoActions_1 = require("./rigoActions");
const generateSidebar = (exercises, learnPath) => {
    const sidebarPath = path.join(learnPath, "sidebar.json");
    let sidebar = {};
    if (fs.existsSync(sidebarPath)) {
        sidebar = JSON.parse(fs.readFileSync(sidebarPath, "utf8"));
    }
    for (const exercise of exercises) {
        sidebar[exercise.slug] = Object.assign(Object.assign({}, sidebar[exercise.slug]), { us: exercise.title });
    }
    fs.writeFileSync(sidebarPath, JSON.stringify(sidebar, null, 2));
    return sidebar;
};
exports.generateSidebar = generateSidebar;
const addExerciseToSidebar = (exerciseSlug, targetLanguage, translatedSlug, learnPath) => {
    const sidebarPath = path.join(learnPath, "sidebar.json");
    let sidebar = {};
    if (fs.existsSync(sidebarPath)) {
        sidebar = JSON.parse(fs.readFileSync(sidebarPath, "utf8"));
    }
    sidebar[exerciseSlug] = Object.assign(Object.assign({}, sidebar[exerciseSlug]), { [targetLanguage]: translatedSlug });
    fs.writeFileSync(sidebarPath, JSON.stringify(sidebar, null, 2));
    return sidebar;
};
exports.addExerciseToSidebar = addExerciseToSidebar;
const checkAndFixSidebar = async (configObj, autoFix = false) => {
    var _a;
    if (configObj.config &&
        fs.existsSync(configObj.config.dirPath + "/sidebar.json")) {
        let hasErrors = false;
        const sidebar = fs.readFileSync(configObj.config.dirPath + "/sidebar.json", "utf8");
        // parse the sidebar.json file
        const sidebarJson = JSON.parse(sidebar);
        const exerciseTranslations = new Set();
        (_a = configObj.exercises) === null || _a === void 0 ? void 0 : _a.map(e => 
        // eslint-disable-next-line
        Object.keys((e.translations || {})).forEach((t) => exerciseTranslations.add(t)));
        // Validation
        for (const [key, value] of Object.entries(sidebarJson)) {
            for (const lang of exerciseTranslations) {
                if (!Object.prototype.hasOwnProperty.call(value, lang)) {
                    hasErrors = true;
                }
            }
        }
        if (hasErrors && autoFix) {
            console_1.default.warning("Filling sidebar.json file with missing translations");
            const sessionPayload = await session_1.default.getPayload();
            const rigoToken = sessionPayload.rigobot.key;
            if (!rigoToken) {
                console_1.default.error("No Rigobot token found, please login first!");
                return false;
            }
            const response = await (0, rigoActions_1.fillSidebarJSON)(rigoToken, {
                needed_translations: JSON.stringify(exerciseTranslations),
                sidebar_json: JSON.stringify(sidebarJson),
            });
            const newSidebarJson = JSON.parse(response.parsed.new_sidebar_file);
            fs.writeFileSync(configObj.config.dirPath + "/sidebar.json", JSON.stringify(newSidebarJson, null, 4));
            console_1.default.info("Sidebar.json was filled with missing translations");
            return true;
        }
        if (hasErrors && !autoFix) {
            return false;
        }
        return true;
    }
    return false;
};
exports.checkAndFixSidebar = checkAndFixSidebar;
const checkAndFixSidebarPure = async (sidebarJson, exercises, rigoToken, autoFix = true) => {
    const exerciseTranslations = new Set();
    for (const e of exercises) {
        for (const lang of Object.keys(e.translations || {})) {
            exerciseTranslations.add(lang);
        }
    }
    let hasErrors = false;
    const fixedSidebar = Object.assign({}, sidebarJson);
    for (const exercise of exercises) {
        const slug = exercise.slug;
        const existingEntry = fixedSidebar[slug];
        if (!existingEntry) {
            hasErrors = true;
            fixedSidebar[slug] = { us: exercise.slug };
            continue;
        }
        for (const lang of exerciseTranslations) {
            if (!Object.prototype.hasOwnProperty.call(existingEntry, lang)) {
                hasErrors = true;
            }
        }
    }
    if (hasErrors && autoFix) {
        if (!rigoToken) {
            console_1.default.error("No Rigobot token provided!");
            return { valid: false };
        }
        console_1.default.warning("Filling sidebar JSON with missing translations or exercises");
        const response = await (0, rigoActions_1.fillSidebarJSON)(rigoToken, {
            needed_translations: JSON.stringify([...exerciseTranslations]),
            sidebar_json: JSON.stringify(fixedSidebar),
        });
        const newSidebarJson = JSON.parse(response.parsed.new_sidebar_file);
        console_1.default.info("Sidebar JSON was fixed");
        return {
            valid: true,
            fixedSidebar: newSidebarJson,
        };
    }
    return {
        valid: !hasErrors,
        fixedSidebar: hasErrors ? fixedSidebar : undefined,
    };
};
exports.checkAndFixSidebarPure = checkAndFixSidebarPure;
