"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const IProjectItemData_1 = require("./IProjectItemData");
const Project_1 = require("./Project");
const Log_1 = require("../core/Log");
const IProjectData_1 = require("./IProjectData");
const StorageUtilities_1 = require("../storage/StorageUtilities");
const EntityTypeDefinition_1 = require("../minecraft/EntityTypeDefinition");
const BehaviorManifestDefinition_1 = require("../minecraft/BehaviorManifestDefinition");
const EnvSettings_1 = require("../devproject/EnvSettings");
const VsCodeLaunchDefinition_1 = require("../devproject/VsCodeLaunchDefinition");
const VsCodeTasksDefinition_1 = require("../devproject/VsCodeTasksDefinition");
const VsCodeExtensionsDefinition_1 = require("../devproject/VsCodeExtensionsDefinition");
const VsCodeSettingsDefinition_1 = require("../devproject/VsCodeSettingsDefinition");
const PrettierRcConfig_1 = require("../devproject/PrettierRcConfig");
const JustConfig_1 = require("../devproject/JustConfig");
class ProjectAutogeneration {
    static async updateProjectAutogeneration(project) {
        let packageItems = 0;
        let envItems = 0;
        let justConfigItems = 0;
        let needsJustConfig = false;
        let needsEslintConfig = false;
        let eslintConfigItems = 0;
        let vsCodeLaunchItems = 0;
        let vsCodeExtensionsItems = 0;
        let vsCodeSettingsItems = 0;
        let vsCodeTasksItems = 0;
        let prettierRcItems = 0;
        const items = project.getItemsCopy();
        for (let i = 0; i < items.length; i++) {
            const item = items[i];
            if (item.itemType === IProjectItemData_1.ProjectItemType.packageJson) {
                packageItems++;
                if (item.file) {
                    await item.file.loadContent();
                    if (item.file.content && typeof item.file.content === "string") {
                        if (item.file.content.indexOf("just-scripts") > 0) {
                            needsJustConfig = true;
                        }
                        if (item.file.content.indexOf("eslint") > 0) {
                            needsEslintConfig = true;
                        }
                    }
                }
            }
            else if (item.itemType === IProjectItemData_1.ProjectItemType.env) {
                envItems++;
            }
            else if (item.itemType === IProjectItemData_1.ProjectItemType.vsCodeLaunchJson) {
                vsCodeLaunchItems++;
            }
            else if (item.itemType === IProjectItemData_1.ProjectItemType.prettierRcJson) {
                prettierRcItems++;
            }
            else if (item.itemType === IProjectItemData_1.ProjectItemType.esLintConfigMjs) {
                eslintConfigItems++;
            }
            else if (item.itemType === IProjectItemData_1.ProjectItemType.justConfigTs) {
                justConfigItems++;
            }
        }
        if (envItems === 0 && (justConfigItems > 0 || needsJustConfig)) {
            project.ensureItemByProjectPath("/.env", IProjectItemData_1.ProjectItemStorageType.singleFile, ".env", IProjectItemData_1.ProjectItemType.env, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (prettierRcItems === 0 && packageItems > 0) {
            project.ensureItemByProjectPath("/.prettierrc.json", IProjectItemData_1.ProjectItemStorageType.singleFile, ".prettierrc.json", IProjectItemData_1.ProjectItemType.prettierRcJson, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (justConfigItems === 0 && needsJustConfig) {
            project.ensureItemByProjectPath("/just.config.ts", IProjectItemData_1.ProjectItemStorageType.singleFile, "just.config.ts", IProjectItemData_1.ProjectItemType.justConfigTs, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (eslintConfigItems === 0 && needsEslintConfig) {
            project.ensureItemByProjectPath("/eslint.config.mjs", IProjectItemData_1.ProjectItemStorageType.singleFile, "eslint.config.mjs", IProjectItemData_1.ProjectItemType.esLintConfigMjs, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (vsCodeLaunchItems === 0 && packageItems > 0 && project.projectFolder) {
            project.ensureItemByProjectPath("/.vscode/launch.json", IProjectItemData_1.ProjectItemStorageType.singleFile, "launch.json", IProjectItemData_1.ProjectItemType.vsCodeLaunchJson, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (vsCodeSettingsItems === 0 && packageItems > 0 && project.projectFolder) {
            project.ensureItemByProjectPath("/.vscode/settings.json", IProjectItemData_1.ProjectItemStorageType.singleFile, "settings.json", IProjectItemData_1.ProjectItemType.vsCodeSettingsJson, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (vsCodeTasksItems === 0 && packageItems > 0 && project.projectFolder) {
            project.ensureItemByProjectPath("/.vscode/tasks.json", IProjectItemData_1.ProjectItemStorageType.singleFile, "tasks.json", IProjectItemData_1.ProjectItemType.vsCodeTasksJson, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (vsCodeExtensionsItems === 0 && packageItems > 0 && project.projectFolder) {
            project.ensureItemByProjectPath("/.vscode/extensions.json", IProjectItemData_1.ProjectItemStorageType.singleFile, "extensions.json", IProjectItemData_1.ProjectItemType.vsCodeExtensionsJson, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        for (let i = 0; i < items.length; i++) {
            const item = items[i];
            if (item.creationType === IProjectItemData_1.ProjectItemCreationType.generated) {
                await ProjectAutogeneration.updateItemAutogeneration(item);
            }
            await ProjectAutogeneration.updateItemAutogeneratedSideFiles(item);
        }
    }
    static async updateItemAutogeneratedSideFiles(item) {
        if (!item.file || !item.project) {
            return;
        }
    }
    static async updateItemAutogeneration(item, contentOnlyUpdate) {
        if (!contentOnlyUpdate) {
            await item.load();
        }
        if (item.file == null || item.creationType !== IProjectItemData_1.ProjectItemCreationType.generated) {
            return;
        }
        if (item.itemType === IProjectItemData_1.ProjectItemType.catalogIndexJs) {
            await item.file.loadContent();
            ProjectAutogeneration.updateCatalogJsContent(item, await ProjectAutogeneration.getCatalogJsContent(item.project));
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.env) {
            item.file.setContent(await EnvSettings_1.default.getContent(item.project, typeof item.file.content === "string" ? item.file.content : undefined));
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.justConfigTs) {
            const justConfigTs = await JustConfig_1.default.ensureOnFile(item.file);
            if (justConfigTs) {
                await justConfigTs.ensureDefault();
                await justConfigTs.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.vsCodeLaunchJson) {
            const vscodelaunch = await VsCodeLaunchDefinition_1.default.ensureOnFile(item.file);
            if (vscodelaunch) {
                await vscodelaunch.ensureMinContent();
                await vscodelaunch.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.vsCodeTasksJson) {
            const vscodetasks = await VsCodeTasksDefinition_1.default.ensureOnFile(item.file);
            if (vscodetasks) {
                await vscodetasks.ensureMinContent();
                await vscodetasks.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.vsCodeExtensionsJson) {
            const vscodeextensions = await VsCodeExtensionsDefinition_1.default.ensureOnFile(item.file);
            if (vscodeextensions) {
                await vscodeextensions.ensureMinContent();
                await vscodeextensions.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.vsCodeSettingsJson) {
            const vscodesettings = await VsCodeSettingsDefinition_1.default.ensureOnFile(item.file);
            if (vscodesettings) {
                await vscodesettings.ensureMinContent();
                await vscodesettings.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.prettierRcJson) {
            const prettierrc = await PrettierRcConfig_1.default.ensureOnFile(item.file);
            if (prettierrc) {
                await prettierrc.ensureMinContent();
                await prettierrc.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.behaviorPackManifestJson) {
            item.file.setContent(await BehaviorManifestDefinition_1.default.getContent(item.project, contentOnlyUpdate));
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.entityTypeBaseJs) {
            const content = await ProjectAutogeneration.getGeneratedTypeJavaScript(item);
            if (content.javaScript !== undefined) {
                item.file.setContent(content.javaScript);
            }
            if (item.project.preferredScriptLanguage === IProjectData_1.ProjectScriptLanguage.typeScript &&
                content.typeScript !== undefined) {
                const file = item.file.parentFolder.ensureFile(StorageUtilities_1.default.getBaseFromName(item.file.name) + ".ts");
                file.setContent(content.typeScript);
            }
            if (item.project.preferredScriptLanguage === IProjectData_1.ProjectScriptLanguage.typeScript &&
                content.typeScript !== undefined) {
                const file = item.file.parentFolder.ensureFile(StorageUtilities_1.default.getBaseFromName(item.file.name) + ".ts");
                file.setContent(content.typeScript);
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.entityTypeBaseTs) {
            const content = await ProjectAutogeneration.getGeneratedTypeJavaScript(item);
            if (content.typeScript !== undefined) {
                item.file.setContent(content.typeScript);
            }
        }
    }
    static async getCatalogJsContent(project) {
        const content = [];
        const behaviorPackRootFolder = await project.ensureDefaultBehaviorPackFolder();
        const items = project.getItemsCopy();
        for (let i = 0; i < items.length; i++) {
            const projectItem = items[i];
            if (projectItem.itemType === IProjectItemData_1.ProjectItemType.worldTest) {
                const file = await projectItem.ensureFileStorage();
                if (file) {
                    const newFileName = StorageUtilities_1.default.getBaseFromName(file.name) + ".gen.js";
                    content.push('import "scripts/' + newFileName + '";');
                }
            }
            else if (projectItem.itemType === IProjectItemData_1.ProjectItemType.js ||
                projectItem.itemType === IProjectItemData_1.ProjectItemType.buildProcessedJs ||
                projectItem.itemType === IProjectItemData_1.ProjectItemType.entityTypeBaseJs ||
                projectItem.itemType === IProjectItemData_1.ProjectItemType.testJs) {
                const file = await projectItem.ensureFileStorage();
                if (file) {
                    let filePath = file.getFolderRelativePath(behaviorPackRootFolder);
                    if (!file.isContentLoaded) {
                        await file.loadContent(false);
                    }
                    if ((file.content !== null || filePath !== null) && filePath !== undefined) {
                        if (filePath.startsWith("/scripts/")) {
                            filePath = filePath.substring(9, filePath.length);
                        }
                        if (filePath.startsWith("/")) {
                            filePath = filePath.substring(1, filePath.length);
                        }
                        content.push('import "' + filePath + '";');
                    }
                }
            }
        }
        return Project_1.AUTOGENERATED_JS_SEPARATOR + "\r\n\r\n" + content.join("\r\n");
    }
    static async updateCatalogJsContent(item, newContent) {
        if (item.file == null || item.file.content instanceof Uint8Array) {
            Log_1.default.unexpectedContentState();
            return;
        }
        if (item.file.content === undefined || item.file.content === null || item.file.content.trim() === "") {
            item.file.setContent(newContent);
            return;
        }
        let updatedContent = item.file.content;
        const autogenToken = updatedContent.indexOf(Project_1.AUTOGENERATED_CONTENT_TOKEN);
        if (autogenToken >= 0) {
            let previous = updatedContent.lastIndexOf("\r", autogenToken);
            if (previous < 0) {
                previous = updatedContent.lastIndexOf("\n", autogenToken);
                if (previous < 0) {
                    previous = 0;
                }
            }
            const previousComment = updatedContent.lastIndexOf("//", autogenToken);
            // we expect \r\n//, but if for some reason the comment has moved, let's only strip from the comment forward.
            if (previousComment > previous + 2) {
                previous = previousComment;
            }
            if (previous >= 0) {
                updatedContent = updatedContent.substring(0, previous);
            }
        }
        updatedContent += newContent;
        item.file.setContent(updatedContent);
    }
    static async getGeneratedTypeJavaScript(item) {
        if (item.projectPath === null || item.projectPath === undefined) {
            return { javaScript: "", typeScript: undefined };
        }
        let typeName = StorageUtilities_1.default.getBaseFromName(StorageUtilities_1.default.getLeafName(item.projectPath));
        if (typeName.endsWith(".base")) {
            typeName = typeName.substring(0, typeName.length - 5);
        }
        const items = item.project.getItemsCopy();
        for (let i = 0; i < items.length; i++) {
            const candItem = items[i];
            if (candItem.itemType === IProjectItemData_1.ProjectItemType.entityTypeBehavior &&
                candItem.projectPath !== null &&
                candItem.projectPath !== undefined) {
                const jsonName = StorageUtilities_1.default.getBaseFromName(StorageUtilities_1.default.getLeafName(candItem.projectPath));
                if (jsonName === typeName) {
                    const jsonFile = await candItem.ensureFileStorage();
                    if (jsonFile !== undefined && jsonFile !== null) {
                        if (jsonFile.manager === undefined) {
                            await EntityTypeDefinition_1.default.ensureOnFile(jsonFile);
                        }
                        if (jsonFile.manager) {
                            const et = jsonFile.manager;
                            const js = et.getScript(false);
                            let ts = undefined;
                            if (item.project.preferredScriptLanguage === IProjectData_1.ProjectScriptLanguage.typeScript) {
                                ts = et.getScript(true);
                            }
                            return { javaScript: js, typeScript: ts };
                        }
                    }
                }
            }
        }
        return { javaScript: "", typeScript: undefined };
    }
}
exports.default = ProjectAutogeneration;

//# sourceMappingURL=../maps/app/ProjectAutogeneration.js.map
