"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
const tslib_1 = require("tslib");
const devkit_1 = require("@nx/devkit");
const path = require("path");
function default_1(tree, schema) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const normalizedNames = generateNameVariants(schema.name, 'entity');
        const normalizedModuleNames = generateNameVariants(schema.moduleName, 'module');
        const targetDir = (0, devkit_1.joinPathFragments)('libs', 'modules', // Ensure 'modules' is part of the path
        normalizedModuleNames.moduleFileName, 'src', 'lib', 'entities', `tag-${normalizedNames.entityFileName}`);
        // Define the new menu item to add
        const newMenuItem = `
   {
     text: \`\${scope}.Tag ${normalizedNames.entityPropertyName}\`,
     path: '',
     icon: ''
   },
`;
        const targetDirModule = (0, devkit_1.joinPathFragments)('libs', 'modules', normalizedModuleNames.moduleFileName);
        (0, devkit_1.generateFiles)(tree, path.join(__dirname, 'files'), targetDir, Object.assign(Object.assign(Object.assign(Object.assign({}, schema), normalizedModuleNames), normalizedNames), { tmpl: '' }));
        function generateNameVariants(baseName, prefix) {
            const formattedNames = (0, devkit_1.names)(baseName);
            //const capitalizedPrefix = prefix.charAt(0).toUpperCase() + prefix.slice(1);
            return {
                [`${prefix}Name`]: formattedNames.name,
                [`${prefix}ClassName`]: formattedNames.className,
                [`${prefix}PropertyName`]: formattedNames.propertyName,
                [`${prefix}FileName`]: formattedNames.fileName,
                [`${prefix}ConstantName`]: formattedNames.constantName,
                [`${prefix}HumanName`]: toSpacedString(formattedNames.name),
            };
        }
        function toSpacedString(str) {
            return str.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase();
        }
        // Update const.ts with the new entity key
        const constFilePath = (0, devkit_1.joinPathFragments)(targetDirModule, 'src/lib/const.ts');
        if (tree.exists(constFilePath)) {
            if (tree.exists(constFilePath)) {
                const originalContent = tree.read(constFilePath, 'utf-8');
                // Construct the new entity object
                const newEntityContent = `
    tag${normalizedNames.entityClassName}: {
      name: 'tag-${normalizedNames.entityPropertyName}',
      title: \`t("tag-${normalizedNames.entityPropertyName}", { scope: "\${config.i18n}" })\`,
      titlePlural: \`t("tag-${normalizedNames.entityPropertyName}Plural", { scope: "\${config.i18n}" })\`,
      icon: 'fa-light fa-default',
    },`;
                // Check if `entities` object already exists
                if (/entities:\s*\{[^}]*\}/.test(originalContent)) {
                    // Append the new entity inside the `entities` object
                    const newContent = originalContent.replace(/(entities:\s*\{)/, `$1${newEntityContent}`);
                    tree.write(constFilePath, newContent);
                }
                else {
                    // If `entities` doesn't exist, add it before closing `RootConfig`
                    const newContent = originalContent.replace(/RootConfig\s*=\s*\{([^}]*config,\s*module:[^}]*)\}/, `RootConfig = {$1, entities: {${newEntityContent}}}`);
                    tree.write(constFilePath, newContent);
                }
            }
        }
        // Append service provider to the existing module.ts file if it exists
        const moduleFilePath = (0, devkit_1.joinPathFragments)(targetDirModule, `src/lib/${normalizedModuleNames.moduleFileName}.module.ts`);
        // Define import and provider strings for the new entity
        const serviceImport = `import { AXMTag${normalizedNames.entityClassName}Service, AXMTag${normalizedNames.entityClassName}ServiceImpl } from './entities';`;
        const serviceProvider = `{
      provide: AXMTag${normalizedNames.entityClassName}Service,
      useClass: AXMTag${normalizedNames.entityClassName}ServiceImpl,
    }`;
        if (tree.exists(moduleFilePath)) {
            const originalContent = tree.read(moduleFilePath, 'utf-8');
            // Add the import if not already present
            const updatedImports = originalContent.includes(serviceImport)
                ? originalContent
                : originalContent.replace(/(@NgModule\(\{)/, `${serviceImport}\n$1`);
            // Add the provider to the providers array if not already present
            const updatedProviders = updatedImports.includes(serviceProvider)
                ? updatedImports
                : updatedImports.replace(/providers:\s*\[/, `providers: [${serviceProvider}, `);
            // Write the updated content back to the module file
            tree.write(moduleFilePath, updatedProviders);
        }
        // Append new menu item to `children` array in `menu.provider.ts`
        const menuProviderFilePath = (0, devkit_1.joinPathFragments)(targetDirModule, 'src/lib/menu.provider.ts');
        if (tree.exists(menuProviderFilePath)) {
            const originalContent = tree.read(menuProviderFilePath, 'utf-8');
            // Find the placeholder in the children array and add the new menu item
            const updatedContent = originalContent.replace(/children:\s*\[\s*<%= menuItems %>\s*\]/, `children: [${newMenuItem}<%= menuItems %>]`);
            // Write the updated content back to the `menu.provider.ts` file
            tree.write(menuProviderFilePath, updatedContent);
        }
        const indexFilePath = (0, devkit_1.joinPathFragments)(targetDirModule, 'src', 'lib', 'entities', 'index.ts');
        // Define the new export line
        const newExportLine = `export * from './tag-${normalizedNames.entityFileName}';\n`;
        // Check if index.ts exists and append the new export line
        if (tree.exists(indexFilePath)) {
            const originalContent = tree.read(indexFilePath, 'utf-8');
            const updatedContent = originalContent.includes(newExportLine)
                ? originalContent
                : `${originalContent}${newExportLine}`;
            tree.write(indexFilePath, updatedContent);
        }
        else {
            // If index.ts does not exist, create it with the new export line
            tree.write(indexFilePath, newExportLine);
        }
    });
}
//# sourceMappingURL=generator.js.map