"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarkdownTop = void 0;
const Utilities_1 = require("../core/Utilities");
const StorageUtilities_1 = require("../storage/StorageUtilities");
const EntityTypeDefinition_1 = require("../minecraft/EntityTypeDefinition");
const DataFormUtilities_1 = require("../dataform/DataFormUtilities");
const LegacyDocumentationDefinition_1 = require("../minecraft/docs/LegacyDocumentationDefinition");
const Log_1 = require("../core/Log");
exports.MarkdownTop = `---
author: mammerla
ms.author: mikeam
title: "{0}"
description: "{1}"
ms.service: minecraft-bedrock-edition
ms.date: 02/11/2025
---
`;
class DocJsonMarkdownDocumentationGenerator {
    async generateMarkdown(formJsonInputFolder, outputFolder) {
        const formsByPath = {};
        await this.loadFormJsonFromFolder(formsByPath, formJsonInputFolder, outputFolder);
        this.exportMarkdownAggregatedPage(formsByPath, outputFolder, "/AnimationsReference/Examples/AnimationController.md", "animations", ["/Animation Controllers/"], "Animation Controllers", "Animation Controllers");
        this.exportMarkdownAggregatedPage(formsByPath, outputFolder, "/AnimationsReference/generated/AnimationGettingStarted.md", "animations", [
            "/Overview/",
            "/Names/",
            "/Getting Started/Adding Animations/",
            "/Getting Started/Animation Hierarchy/",
            "/Key Frames/",
            "/Transforms/",
        ], "Animation Getting Started", "Animation Getting Started");
        this.exportMarkdownAggregatedPage(formsByPath, outputFolder, "/AnimationsReference/generated/AnimationRenderController.md", "animations", ["/Render Controllers/"], "Animation and Render Controllers", "Animation and Render Controllers");
        this.exportMarkdownAggregatedPage(formsByPath, outputFolder, "/AnimationsReference/Examples/AnimationUpgrading.md", "animations", [
            "/Getting Started/Upgrade from v1.7 Beta to v1.8/",
            "/Getting Started/Upgrade from v1.8 Beta to v1.10/",
            "/Getting Started/Upgrade from v1.10 to v1.17.30/",
            "/Getting Started/Upgrade from v1.17.30 to v1.18.10/",
            "/Getting Started/Upgrade from v1.18.10 to v1.18.20/",
        ], "Animation Controllers", "Animation Controllers");
    }
    getFileNameFromBaseName(baseName) {
        let fileName = baseName;
        if (fileName.startsWith("minecraft_on_")) {
            fileName = "minecraftTrigger_" + baseName.substring(10);
        }
        else if (fileName.startsWith("minecraft_")) {
            fileName = "minecraftComponent_" + baseName.substring(10);
        }
        return fileName;
    }
    async exportMarkdownAggregatedPage(formsByPath, outputFolder, filePath, docCatalogName, docNodePaths, category, categoryExtended) {
        const targetFile = await outputFolder.ensureFileFromRelativePath(filePath);
        if (!targetFile) {
            return;
        }
        const docLines = [];
        docLines.push(Utilities_1.default.stringFormat(exports.MarkdownTop, category + " Documentation - " + category, "A reference document describing all current " + category));
        docLines.push("# " + category + "\r\n");
        for (const docNodePath of docNodePaths) {
            const docNode = await LegacyDocumentationDefinition_1.default.loadNode(docCatalogName, docNodePath, true);
            if (docNode) {
                if (docNode.nodes) {
                    docLines.push("## " + docNode.name);
                    for (const childNode of docNode.nodes) {
                        if (childNode.description) {
                            docLines.push("");
                            docLines.push(...childNode.description);
                        }
                        if (childNode.examples) {
                            for (const example of childNode.examples) {
                                if (example.name && example.text) {
                                    docLines.push("\r\n### " + example.name);
                                    docLines.push(...example.text);
                                }
                            }
                        }
                    }
                }
            }
            else {
                Log_1.default.debugAlert("Could not find '" + docNodePath + "'");
            }
        }
        targetFile.setContent(docLines.join("\r\n"));
        await targetFile.saveContent();
    }
    appendForm(form, content) {
        if (form.description) {
            let descrip = form.description.trim();
            if (descrip.length > 10 && !descrip.endsWith(".")) {
                descrip += ".";
            }
            content.push(descrip + "\r\n");
        }
        const subContent = [];
        content.push("\r\n## Properties\r\n");
        content.push("|Name       |Default Value |Type |Description |Example Values |");
        content.push("|:----------|:-------------|:----|:-----------|:------------- |");
        form.fields.sort((a, b) => {
            return a.id.localeCompare(b.id);
        });
        for (const field of form.fields) {
            let fieldRow = "| " + field.id + " | ";
            if (field.defaultValue !== undefined) {
                fieldRow += field.defaultValue;
            }
            else {
                fieldRow += "*not set*";
            }
            fieldRow += " | " + DataFormUtilities_1.default.getFieldTypeDescription(field.dataType) + " | ";
            if (field.description) {
                fieldRow += field.description;
            }
            fieldRow += " | ";
            if (field.subForm && field.subForm.fields.length > 0) {
                subContent.push("\r\n### Sub item: " + field.id + "\r\n");
                this.appendForm(field.subForm, subContent);
            }
            if (field.samples) {
                let samplesAdded = 0;
                const samplesUsed = [];
                for (const samplePath in field.samples) {
                    let sampleArr = field.samples[samplePath];
                    if (sampleArr && samplesAdded < 3) {
                        const sampleSet = {};
                        for (const sample of sampleArr) {
                            const sampleVal = JSON.stringify(sample.content);
                            if (!samplesUsed.includes(sampleVal)) {
                                samplesUsed.push(sampleVal);
                                const baseName = StorageUtilities_1.default.getBaseFromName(StorageUtilities_1.default.getLeafName(samplePath));
                                samplesAdded++;
                                const key = baseName.substring(0, 1).toUpperCase() + baseName.substring(1);
                                if (!sampleSet[key]) {
                                    sampleSet[key] = "`" + sampleVal + "`";
                                }
                                else {
                                    sampleSet[key] = sampleSet[key] + ", `" + sampleVal + "`";
                                }
                            }
                        }
                        let exampleAdded = false;
                        for (const key in sampleSet) {
                            if (exampleAdded) {
                                fieldRow += ", ";
                            }
                            fieldRow += Utilities_1.default.humanifyMinecraftName(key) + ": " + sampleSet[key];
                            exampleAdded = true;
                        }
                    }
                }
            }
            fieldRow += " | ";
            content.push(fieldRow);
        }
        content.push(...subContent);
    }
    async saveMarkdownDocFromForm(markdownFile, form, baseName, category, categoryExtended) {
        const content = [];
        let canonName = EntityTypeDefinition_1.default.getComponentFromBaseFileName(baseName);
        content.push(Utilities_1.default.stringFormat(exports.MarkdownTop, category + " Documentation - " + canonName, "Describes the " + canonName + " " + categoryExtended));
        content.push("# " + category + " Documentation - " + canonName + "\r\n");
        this.appendForm(form, content);
        if (form.samples) {
            content.push("\r\n## Samples\r\n");
            let samplesAdded = 0;
            for (const samplePath in form.samples) {
                let sampleArr = form.samples[samplePath];
                if (sampleArr && samplesAdded < 3) {
                    const baseName = StorageUtilities_1.default.getBaseFromName(StorageUtilities_1.default.getLeafName(samplePath));
                    let targetPath = samplePath;
                    if (targetPath.startsWith("/vanilla")) {
                        targetPath = "https://github.com/Mojang/bedrock-samples/tree/preview" + targetPath.substring(8);
                    }
                    content.push("### [" + baseName.substring(0, 1).toUpperCase() + baseName.substring(1) + "](" + targetPath + ")");
                    for (const sample of sampleArr) {
                        if (sampleArr.length > 1) {
                            content.push("\r\nAt " + sample.path + ": ");
                        }
                        if (typeof sample.content === "object" || Array.isArray(sample.content)) {
                            content.push("\r\n```json\r\n" + JSON.stringify(sample.content, undefined, 2) + "\r\n```\r\n");
                        }
                        else {
                            content.push("\r\n`" + sample.content + "`\r\n");
                        }
                    }
                }
            }
        }
        markdownFile.setContent(content.join("\r\n"));
        await markdownFile.saveContent();
    }
    getFormsFromFilter(formsByPath, formsPath) {
        const filteredList = {};
        for (const formPath in formsByPath) {
            if (formPath.toLowerCase().startsWith(formsPath) &&
                formsByPath[formPath] &&
                (formsPath.indexOf("behavior") >= 0 || formPath.indexOf("behavior") < 0) &&
                (formsPath.indexOf("_on") >= 0 || formPath.indexOf("_on") < 0)) {
                filteredList[formPath] = formsByPath[formPath];
            }
        }
        return filteredList;
    }
    async loadFormJsonFromFolder(formsByPath, inputFolder, outputFolder) {
        await inputFolder.load();
        const fileList = { files: [], folders: [] };
        for (const folderName in inputFolder.folders) {
            const folder = inputFolder.folders[folderName];
            if (folder) {
                await this.loadFormJsonFromFolder(formsByPath, folder, outputFolder.ensureFolder(folderName));
                fileList.folders.push(folderName);
            }
        }
        for (const fileName in inputFolder.files) {
            const file = inputFolder.files[fileName];
            if (file) {
                await file.loadContent();
                const jsonO = StorageUtilities_1.default.getJsonObject(file);
                if (jsonO) {
                    if (Utilities_1.default.isUsableAsObjectKey(file.storageRelativePath)) {
                        formsByPath[file.storageRelativePath] = jsonO;
                    }
                }
            }
        }
    }
}
exports.default = DocJsonMarkdownDocumentationGenerator;

//# sourceMappingURL=../maps/docgen/DocJsonMarkdownDocumentationGenerator.js.map
