import * as _ from 'lodash-es';
import chalk from 'chalk';
import { isFilePending } from 'mem-fs-editor/state';
import BaseApplicationGenerator from '../base-application/index.mjs';
import { GENERATOR_ANGULAR, GENERATOR_CLIENT, GENERATOR_LANGUAGES } from '../generator-list.mjs';
import { defaultLanguage } from '../languages/support/index.mjs';
import { writeEntitiesFiles, postWriteEntitiesFiles, cleanupEntitiesFiles } from './entity-files-angular.mjs';
import { writeFiles } from './files-angular.mjs';
import cleanupOldFilesTask from './cleanup.mjs';
import { clientFrameworkTypes } from '../../jdl/jhipster/index.mjs';
import { buildAngularFormPath as angularFormPath, addEntitiesRoute, addToEntitiesMenu, translateAngularFilesTransform, isTranslatedAngularFile, addRoute, addItemToAdminMenu, addIconImport, } from './support/index.mjs';
import { generateEntityClientEnumImports as getClientEnumImportsFormat, getTypescriptKeyType as getTSKeyType, generateTestEntityId as getTestEntityId, generateTestEntityPrimaryKey as getTestEntityPrimaryKey, generateTypescriptTestEntity as generateTestEntity, } from '../client/support/index.mjs';
import { createNeedleCallback } from '../base/support/index.mjs';
const { ANGULAR } = clientFrameworkTypes;
export default class AngularGenerator extends BaseApplicationGenerator {
    localEntities;
    async beforeQueue() {
        if (!this.fromBlueprint) {
            await this.composeWithBlueprints(GENERATOR_ANGULAR);
        }
        if (!this.delegateToBlueprint) {
            await this.dependsOnJHipster(GENERATOR_CLIENT);
            await this.dependsOnJHipster(GENERATOR_LANGUAGES);
        }
    }
    get loading() {
        return this.asLoadingTaskGroup({
            loadPackageJson({ application }) {
                this.loadNodeDependenciesFromPackageJson(application.nodeDependencies, this.fetchFromInstalledJHipster(GENERATOR_ANGULAR, 'resources', 'package.json'));
            },
        });
    }
    get [BaseApplicationGenerator.LOADING]() {
        return this.asLoadingTaskGroup(this.delegateTasksToBlueprint(() => this.loading));
    }
    get preparing() {
        return this.asPreparingTaskGroup({
            prepareForTemplates({ application }) {
                application.webappEnumerationsDir = `${application.clientSrcDir}app/entities/enumerations/`;
                application.angularLocaleId = application.nativeLanguageDefinition.angularLocale ?? defaultLanguage.angularLocale;
            },
            addNeedles({ source, application }) {
                source.addEntitiesToClient = param => {
                    const { application, entities } = param;
                    this.addEntitiesToModule({ application, entities });
                    this.addEntitiesToMenu({ application, entities });
                };
                source.addAdminRoute = (args) => this.editFile(`${application.srcMainWebapp}app/admin/admin-routing.module.ts`, addRoute({
                    needle: 'add-admin-route',
                    ...args,
                }));
                source.addItemToAdminMenu = (args) => {
                    this.editFile(`${application.srcMainWebapp}app/layouts/navbar/navbar.component.html`, addItemToAdminMenu({
                        enableTranslation: application.enableTranslation,
                        jhiPrefix: application.jhiPrefix,
                        ...args,
                    }));
                    if (args.icon) {
                        source.addIconImport({ icon: args.icon });
                    }
                };
                source.addIconImport = args => {
                    const iconsPath = `${application.srcMainWebapp}app/config/font-awesome-icons.ts`;
                    const ignoreNonExisting = this.sharedData.getControl().ignoreNeedlesError && 'Icon imports not updated with icon';
                    this.editFile(iconsPath, { ignoreNonExisting }, addIconImport(args));
                };
                source.addWebpackConfig = args => {
                    const webpackPath = `${application.clientRootDir}webpack/webpack.custom.js`;
                    const ignoreNonExisting = this.sharedData.getControl().ignoreNeedlesError && 'Webpack configuration file not found';
                    this.editFile(webpackPath, { ignoreNonExisting }, createNeedleCallback({
                        needle: 'jhipster-needle-add-webpack-config',
                        contentToAdd: `,${args.config}`,
                    }));
                };
            },
        });
    }
    get [BaseApplicationGenerator.PREPARING]() {
        return this.asPreparingTaskGroup(this.delegateTasksToBlueprint(() => this.preparing));
    }
    get default() {
        return this.asDefaultTaskGroup({
            loadEntities() {
                const entities = this.sharedData.getEntities().map(({ entity }) => entity);
                this.localEntities = entities.filter(entity => !entity.builtIn && !entity.skipClient);
            },
        });
    }
    get [BaseApplicationGenerator.DEFAULT]() {
        return this.asDefaultTaskGroup(this.delegateTasksToBlueprint(() => this.default));
    }
    get writing() {
        return this.asWritingTaskGroup({
            cleanupOldFilesTask,
            writeFiles,
            queueTranslateTransform({ control, application }) {
                this.queueTransformStream(translateAngularFilesTransform(control.getWebappTranslation, application.enableTranslation), {
                    name: 'translating webapp',
                    streamOptions: { filter: file => isFilePending(file) && isTranslatedAngularFile(file) },
                });
            },
        });
    }
    get [BaseApplicationGenerator.WRITING]() {
        return this.delegateTasksToBlueprint(() => this.writing);
    }
    get writingEntities() {
        return this.asWritingEntitiesTaskGroup({
            cleanupEntitiesFiles,
            writeEntitiesFiles,
        });
    }
    get [BaseApplicationGenerator.WRITING_ENTITIES]() {
        return this.delegateTasksToBlueprint(() => this.writingEntities);
    }
    get postWritingEntities() {
        return this.asPostWritingEntitiesTaskGroup({
            postWriteEntitiesFiles,
        });
    }
    get [BaseApplicationGenerator.POST_WRITING_ENTITIES]() {
        return this.delegateTasksToBlueprint(() => this.postWritingEntities);
    }
    get end() {
        return this.asEndTaskGroup({
            end({ application }) {
                this.log.ok('Angular application generated successfully.');
                this.log.log(chalk.green(`  Start your Webpack development server with:
  ${chalk.yellow.bold(`${application.nodePackageManager} start`)}
`));
            },
        });
    }
    get [BaseApplicationGenerator.END]() {
        return this.asEndTaskGroup(this.delegateTasksToBlueprint(() => this.end));
    }
    addVendorSCSSStyle(style, comment) {
        this.needleApi.clientAngular.addVendorSCSSStyle(style, comment);
    }
    addAdminToModule(appName, adminAngularName, adminFolderName, adminFileName, enableTranslation) {
        this.needleApi.clientAngular.addToAdminModule(appName, adminAngularName, adminFolderName, adminFileName, enableTranslation);
    }
    addAdminRoute(route, modulePath, moduleName, pageTitle) {
        this.needleApi.clientAngular.addAdminRoute(route, modulePath, moduleName, pageTitle);
    }
    addAngularModule(appName, angularName, folderName, fileName, enableTranslation) {
        this.needleApi.clientAngular.addModule(appName, angularName, folderName, fileName, enableTranslation);
    }
    addIcon(iconName) {
        this.needleApi.clientAngular.addIcon(iconName);
    }
    addElementToAdminMenu(routerName, iconName, enableTranslation, translationKeyMenu = _.camelCase(routerName), jhiPrefix) {
        this.needleApi.clientAngular.addElementToAdminMenu(routerName, iconName, enableTranslation, translationKeyMenu, jhiPrefix);
    }
    addEntitiesToMenu({ application, entities }) {
        const filePath = `${application.clientSrcDir}app/layouts/navbar/navbar.component.html`;
        const ignoreNonExisting = chalk.yellow('Reference to entities not added to menu.');
        const editCallback = addToEntitiesMenu({ application, entities });
        this.editFile(filePath, { ignoreNonExisting }, editCallback);
    }
    addEntitiesToModule({ application, entities }) {
        const filePath = `${application.clientSrcDir}app/entities/entity-routing.module.ts`;
        const ignoreNonExisting = chalk.yellow(`Route(s) not added to ${filePath}.`);
        const addRouteCallback = addEntitiesRoute({ application, entities });
        this.editFile(filePath, { ignoreNonExisting }, addRouteCallback);
    }
    addMainSCSSStyle(style, comment) {
        this.needleApi.clientAngular.addGlobalSCSSStyle(style, comment);
    }
    generateEntityClientEnumImports(fields) {
        return getClientEnumImportsFormat(fields, ANGULAR);
    }
    getTypescriptKeyType(primaryKey) {
        return getTSKeyType(primaryKey);
    }
    generateTestEntityId(primaryKey, index = 0, wrapped = true) {
        return getTestEntityId(primaryKey, index, wrapped);
    }
    generateTestEntityPrimaryKey(primaryKey, index) {
        return getTestEntityPrimaryKey(primaryKey, index);
    }
    generateTypescriptTestEntity(references, additionalFields) {
        return generateTestEntity(references, additionalFields);
    }
    buildAngularFormPath(reference, prefix = []) {
        return angularFormPath(reference, prefix);
    }
    addElementToMenu(routerName, iconName, enableTranslation, clientFramework, translationKeyMenu = _.camelCase(routerName)) {
        this.needleApi.clientAngular.addElementToMenu(routerName, iconName, enableTranslation, translationKeyMenu);
    }
}
