"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const WorldTestManager_1 = require("../script/WorldTestManager");
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");
const NpmPackageDefinition_1 = require("../devproject/NpmPackageDefinition");
class ProjectAutogeneration {
    static async updateProjectAutogeneration(project, createNewArtifacts) {
        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++;
                const itemFile = item.primaryFile;
                if (itemFile) {
                    if (!itemFile.isContentLoaded) {
                        await itemFile.loadContent();
                    }
                    if (itemFile.content && typeof itemFile.content === "string") {
                        if (itemFile.content.indexOf("just-scripts") > 0) {
                            needsJustConfig = true;
                        }
                        if (itemFile.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) && createNewArtifacts) {
            project.ensureItemByProjectPath("/.env", IProjectItemData_1.ProjectItemStorageType.singleFile, ".env", IProjectItemData_1.ProjectItemType.env, Project_1.FolderContext.unknown, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (prettierRcItems === 0 && packageItems > 0 && createNewArtifacts) {
            project.ensureItemByProjectPath("/.prettierrc.json", IProjectItemData_1.ProjectItemStorageType.singleFile, ".prettierrc.json", IProjectItemData_1.ProjectItemType.prettierRcJson, Project_1.FolderContext.unknown, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (justConfigItems === 0 && needsJustConfig && createNewArtifacts) {
            project.ensureItemByProjectPath("/just.config.ts", IProjectItemData_1.ProjectItemStorageType.singleFile, "just.config.ts", IProjectItemData_1.ProjectItemType.justConfigTs, Project_1.FolderContext.unknown, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (eslintConfigItems === 0 && needsEslintConfig && createNewArtifacts) {
            project.ensureItemByProjectPath("/eslint.config.mjs", IProjectItemData_1.ProjectItemStorageType.singleFile, "eslint.config.mjs", IProjectItemData_1.ProjectItemType.esLintConfigMjs, Project_1.FolderContext.unknown, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (vsCodeLaunchItems === 0 && packageItems > 0 && project.projectFolder && createNewArtifacts) {
            project.ensureItemByProjectPath("/.vscode/launch.json", IProjectItemData_1.ProjectItemStorageType.singleFile, "launch.json", IProjectItemData_1.ProjectItemType.vsCodeLaunchJson, Project_1.FolderContext.unknown, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (vsCodeSettingsItems === 0 && packageItems > 0 && project.projectFolder && createNewArtifacts) {
            project.ensureItemByProjectPath("/.vscode/settings.json", IProjectItemData_1.ProjectItemStorageType.singleFile, "settings.json", IProjectItemData_1.ProjectItemType.vsCodeSettingsJson, Project_1.FolderContext.unknown, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (vsCodeTasksItems === 0 && packageItems > 0 && project.projectFolder && createNewArtifacts) {
            project.ensureItemByProjectPath("/.vscode/tasks.json", IProjectItemData_1.ProjectItemStorageType.singleFile, "tasks.json", IProjectItemData_1.ProjectItemType.vsCodeTasksJson, Project_1.FolderContext.unknown, undefined, IProjectItemData_1.ProjectItemCreationType.generated);
        }
        if (vsCodeExtensionsItems === 0 && packageItems > 0 && project.projectFolder && createNewArtifacts) {
            project.ensureItemByProjectPath("/.vscode/extensions.json", IProjectItemData_1.ProjectItemStorageType.singleFile, "extensions.json", IProjectItemData_1.ProjectItemType.vsCodeExtensionsJson, Project_1.FolderContext.unknown, 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.primaryFile || !item.project) {
            return;
        }
        if (item.itemType === IProjectItemData_1.ProjectItemType.worldTest) {
            const worldTestManager = await WorldTestManager_1.default.ensureOnFile(item.primaryFile);
            if (worldTestManager) {
                await worldTestManager.persistSideFiles(item.project);
            }
        }
    }
    static async updateItemAutogeneration(item, contentOnlyUpdate) {
        if (!contentOnlyUpdate && !item.isContentLoaded) {
            await item.loadContent();
        }
        if (item.primaryFile == null || item.creationType !== IProjectItemData_1.ProjectItemCreationType.generated) {
            return;
        }
        if (item.itemType === IProjectItemData_1.ProjectItemType.catalogIndexJs) {
            if (!item.primaryFile.isContentLoaded) {
                await item.primaryFile.loadContent();
            }
            ProjectAutogeneration.updateCatalogJsContent(item, await ProjectAutogeneration.getCatalogJsContent(item.project));
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.env) {
            item.primaryFile.setContent(await EnvSettings_1.default.getContent(item.project, typeof item.primaryFile.content === "string" ? item.primaryFile.content : undefined));
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.justConfigTs) {
            const justConfigTs = await JustConfig_1.default.ensureOnFile(item.primaryFile);
            if (justConfigTs) {
                await justConfigTs.ensureDefault();
                await justConfigTs.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.vsCodeLaunchJson) {
            const vscodelaunch = await VsCodeLaunchDefinition_1.default.ensureOnFile(item.primaryFile);
            if (vscodelaunch) {
                await vscodelaunch.ensureMinContent();
                await vscodelaunch.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.vsCodeTasksJson) {
            const vscodetasks = await VsCodeTasksDefinition_1.default.ensureOnFile(item.primaryFile);
            if (vscodetasks) {
                await vscodetasks.ensureMinContent();
                await vscodetasks.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.vsCodeExtensionsJson) {
            const vscodeextensions = await VsCodeExtensionsDefinition_1.default.ensureOnFile(item.primaryFile);
            if (vscodeextensions) {
                await vscodeextensions.ensureMinContent();
                await vscodeextensions.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.vsCodeSettingsJson) {
            const vscodesettings = await VsCodeSettingsDefinition_1.default.ensureOnFile(item.primaryFile);
            if (vscodesettings) {
                await vscodesettings.ensureMinContent();
                await vscodesettings.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.prettierRcJson) {
            const prettierrc = await PrettierRcConfig_1.default.ensureOnFile(item.primaryFile);
            if (prettierrc) {
                await prettierrc.ensureMinContent();
                await prettierrc.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.packageJson) {
            const packageJson = await NpmPackageDefinition_1.default.ensureOnFile(item.primaryFile);
            if (packageJson) {
                await packageJson.ensureMinContent(item.project);
                await packageJson.save();
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.behaviorPackManifestJson) {
            item.primaryFile.setContent(await BehaviorManifestDefinition_1.default.getContent(item.project, contentOnlyUpdate));
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.entityTypeBaseJs) {
            const content = await ProjectAutogeneration.getGeneratedEntityTypeScript(item);
            if (content.javaScript !== undefined) {
                item.primaryFile.setContent(content.javaScript);
            }
            if (item.project.preferredScriptLanguage === IProjectData_1.ProjectScriptLanguage.typeScript &&
                content.typeScript !== undefined) {
                const file = item.primaryFile.parentFolder.ensureFile(StorageUtilities_1.default.getBaseFromName(item.primaryFile.name) + ".ts");
                file.setContent(content.typeScript);
            }
            if (item.project.preferredScriptLanguage === IProjectData_1.ProjectScriptLanguage.typeScript &&
                content.typeScript !== undefined) {
                const file = item.primaryFile.parentFolder.ensureFile(StorageUtilities_1.default.getBaseFromName(item.primaryFile.name) + ".ts");
                file.setContent(content.typeScript);
            }
        }
        else if (item.itemType === IProjectItemData_1.ProjectItemType.entityTypeBaseTs) {
            const content = await ProjectAutogeneration.getGeneratedEntityTypeScript(item);
            if (content.typeScript !== undefined) {
                item.primaryFile.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.loadFileContent();
                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.loadFileContent();
                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 + "\n\n" + content.join("\n");
    }
    static async updateCatalogJsContent(item, newContent) {
        if (item.primaryFile == null || item.primaryFile.content instanceof Uint8Array) {
            Log_1.default.unexpectedContentState();
            return;
        }
        if (item.primaryFile.content === undefined ||
            item.primaryFile.content === null ||
            item.primaryFile.content.trim() === "") {
            item.primaryFile.setContent(newContent);
            return;
        }
        let updatedContent = item.primaryFile.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 \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.primaryFile.setContent(updatedContent);
    }
    static async getGeneratedEntityTypeScript(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.loadFileContent();
                    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
