import { camelCase } from 'lodash-es';
import chalk from 'chalk';
import { isFileStateModified } from 'mem-fs-editor/state';
import BaseApplicationGenerator from '../base-application/index.js';
import { GENERATOR_ANGULAR, GENERATOR_CLIENT, GENERATOR_LANGUAGES } from '../generator-list.js';
import { defaultLanguage } from '../languages/support/index.js';
import { writeEntitiesFiles, postWriteEntitiesFiles, cleanupEntitiesFiles } from './entity-files-angular.js';
import { writeFiles } from './files-angular.js';
import cleanupOldFilesTask from './cleanup.js';
import { clientFrameworkTypes } from '../../jdl/jhipster/index.js';
import { buildAngularFormPath as angularFormPath, addEntitiesRoute, addToEntitiesMenu, translateAngularFilesTransform, isTranslatedAngularFile, addRoute, addItemToAdminMenu, addIconImport, } from './support/index.js';
import { generateEntityClientEnumImports as getClientEnumImportsFormat, getTypescriptKeyType as getTSKeyType, generateTestEntityId as getTestEntityId, generateTestEntityPrimaryKey as getTestEntityPrimaryKey, generateTypescriptTestEntity as generateTestEntity, } from '../client/support/index.js';
import { createNeedleCallback, mutateData } from '../base/support/index.js';
const { ANGULAR } = clientFrameworkTypes;
export default class AngularGenerator extends BaseApplicationGenerator {
    localEntities;
    async beforeQueue() {
        if (!this.fromBlueprint) {
            await this.composeWithBlueprints();
        }
        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.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.routes.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.delegateTasksToBlueprint(() => this.preparing);
    }
    get preparingEachEntity() {
        return this.asPreparingEachEntityTaskGroup({
            prepareEntity({ entity }) {
                const asAuthorities = authorities => (authorities.length > 0 ? authorities.map(auth => `'${auth}'`).join(', ') : undefined);
                mutateData(entity, {
                    entityAngularAuthorities: asAuthorities(entity.entityAuthority?.split(',') ?? []),
                    entityAngularReadAuthorities: asAuthorities([
                        ...(entity.entityAuthority?.split(',') ?? []),
                        ...(entity.entityReadAuthority?.split(',') ?? []),
                    ]),
                });
            },
        });
    }
    get [BaseApplicationGenerator.PREPARING_EACH_ENTITY]() {
        return this.delegateTasksToBlueprint(() => this.preparingEachEntity);
    }
    get preparingEachEntityField() {
        return this.asPreparingEachEntityFieldTaskGroup({
            prepareField({ field }) {
                mutateData(field, {
                    fieldTsDefaultValue: ({ fieldTsDefaultValue, defaultValue, fieldTypeCharSequence, fieldTypeTimed }) => {
                        let returnValue;
                        if (fieldTsDefaultValue !== undefined || defaultValue !== undefined) {
                            let fieldDefaultValue;
                            if (fieldTsDefaultValue !== undefined) {
                                fieldDefaultValue = fieldTsDefaultValue;
                            }
                            else {
                                fieldDefaultValue = defaultValue;
                            }
                            fieldDefaultValue = String(fieldDefaultValue).replace(/'/g, "\\'");
                            if (fieldTypeCharSequence) {
                                returnValue = `'${fieldDefaultValue}'`;
                            }
                            else if (fieldTypeTimed) {
                                returnValue = `dayjs('${fieldDefaultValue}')`;
                            }
                            else {
                                returnValue = fieldDefaultValue;
                            }
                        }
                        return returnValue;
                    },
                });
            },
        });
    }
    get [BaseApplicationGenerator.PREPARING_EACH_ENTITY_FIELD]() {
        return this.delegateTasksToBlueprint(() => this.preparingEachEntityField);
    }
    get default() {
        return this.asDefaultTaskGroup({
            loadEntities() {
                const entities = this.sharedData.getEntities().map(({ entity }) => entity);
                this.localEntities = entities.filter(entity => !entity.builtIn && !entity.skipClient);
            },
            queueTranslateTransform({ control, application }) {
                const { enableTranslation, jhiPrefix } = application;
                this.queueTransformStream({
                    name: 'translating angular application',
                    filter: file => isFileStateModified(file) && file.path.startsWith(this.destinationPath()) && isTranslatedAngularFile(file),
                    refresh: false,
                }, translateAngularFilesTransform(control.getWebappTranslation, { enableTranslation, jhiPrefix }));
            },
        });
    }
    get [BaseApplicationGenerator.DEFAULT]() {
        return this.delegateTasksToBlueprint(() => this.default);
    }
    get writing() {
        return this.asWritingTaskGroup({
            cleanupOldFilesTask,
            writeFiles,
        });
    }
    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 postWriting() {
        return this.asPostWritingTaskGroup({
            addWebsocketDependencies({ application }) {
                const { authenticationTypeSession, communicationSpringWebsocket, nodeDependencies } = application;
                const dependencies = {};
                if (communicationSpringWebsocket) {
                    if (authenticationTypeSession) {
                        dependencies['ngx-cookie-service'] = nodeDependencies['ngx-cookie-service'];
                    }
                    this.packageJson.merge({
                        dependencies: {
                            'sockjs-client': nodeDependencies['sockjs-client'],
                            '@stomp/rx-stomp': nodeDependencies['@stomp/rx-stomp'],
                            ...dependencies,
                        },
                        devDependencies: {
                            '@types/sockjs-client': nodeDependencies['@types/sockjs-client'],
                        },
                    });
                }
            },
        });
    }
    get [BaseApplicationGenerator.POST_WRITING]() {
        return this.delegateTasksToBlueprint(() => this.postWriting);
    }
    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.delegateTasksToBlueprint(() => this.end);
    }
    addVendorSCSSStyle(style, comment) {
        this.needleApi.clientAngular.addVendorSCSSStyle(style, comment);
    }
    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.routes.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);
    }
}
