"use strict";
/**
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
 */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerLocale = registerLocale;
const schematics_1 = require("@angular/cdk/schematics");
const schematics_2 = require("@angular-devkit/schematics");
const utility_1 = require("@schematics/angular/utility");
const change_1 = require("@schematics/angular/utility/change");
const app_config_1 = require("@schematics/angular/utility/standalone/app_config");
const util_1 = require("@schematics/angular/utility/standalone/util");
const chalk_1 = require("chalk");
const ts = require("typescript");
const apply_changes_1 = require("../../utils/apply-changes");
function registerLocale(options) {
    return (host) => __awaiter(this, void 0, void 0, function* () {
        const workspace = yield (0, utility_1.readWorkspace)(host);
        const project = (0, schematics_1.getProjectFromWorkspace)(workspace, options.project);
        const mainFile = (0, schematics_1.getProjectMainFile)(project);
        if ((0, schematics_1.isStandaloneApp)(host, mainFile)) {
            return registerLocaleInStandaloneApp(mainFile, options);
        }
        else {
            return registerLocaleInAppModule(mainFile, options);
        }
    });
}
/**
 * Safely creates an import change, returning NoopChange if the moduleSource is invalid
 * or if the import already exists.
 */
function safeInsertImport(moduleSource, filePath, symbolName, fileName, isDefault = false) {
    if (!moduleSource) {
        console.log();
        console.log((0, chalk_1.yellow)(`Could not insert import for ${symbolName} in file (${(0, chalk_1.blue)(filePath)}).`));
        console.log((0, chalk_1.yellow)(`The source file is invalid.`));
        return new change_1.NoopChange();
    }
    // Check if the import already exists
    const allImports = (0, schematics_1.findNodes)(moduleSource, ts.SyntaxKind.ImportDeclaration);
    if (!allImports) {
        return new change_1.NoopChange();
    }
    const importExists = allImports.some(node => {
        // Make sure it's an import declaration
        if (!ts.isImportDeclaration(node)) {
            return false;
        }
        if (!node.moduleSpecifier) {
            return false;
        }
        // Check if this import is from the same file
        if (!ts.isStringLiteral(node.moduleSpecifier)) {
            return false;
        }
        const importPath = node.moduleSpecifier.text;
        if (importPath !== fileName) {
            return false;
        }
        // Check if the symbol is already imported
        if (!node.importClause) {
            return false;
        }
        const namedBindings = node.importClause.namedBindings;
        if (!namedBindings) {
            return false;
        }
        if (ts.isNamedImports(namedBindings)) {
            return namedBindings.elements.some(element => element.name.text === symbolName);
        }
        return false;
    });
    if (importExists) {
        return new change_1.NoopChange();
    }
    try {
        return (0, schematics_1.insertImport)(moduleSource, filePath, symbolName, fileName, isDefault);
    }
    catch (e) {
        console.log();
        console.log((0, chalk_1.yellow)(`Could not insert import for ${symbolName} in file (${(0, chalk_1.blue)(filePath)}).`));
        console.log((0, chalk_1.yellow)(`Error: ${e.message}`));
        return new change_1.NoopChange();
    }
}
function registerLocaleInAppModule(mainFile, options) {
    return (host) => __awaiter(this, void 0, void 0, function* () {
        const appModulePath = (0, schematics_1.getAppModulePath)(host, mainFile);
        const moduleSource = (0, schematics_1.parseSourceFile)(host, appModulePath);
        const locale = options.locale || 'en_US';
        const localePrefix = locale.split('_')[0];
        (0, apply_changes_1.applyChangesToFile)(host, appModulePath, [
            safeInsertImport(moduleSource, appModulePath, 'provideNzI18n', 'ng-zorro-antd/i18n'),
            safeInsertImport(moduleSource, appModulePath, locale, 'ng-zorro-antd/i18n'),
            safeInsertImport(moduleSource, appModulePath, 'registerLocaleData', '@angular/common'),
            safeInsertImport(moduleSource, appModulePath, localePrefix, `@angular/common/locales/${localePrefix}`, true),
            registerLocaleData(moduleSource, appModulePath, localePrefix),
            ...insertI18nTokenProvide(moduleSource, appModulePath, locale)
        ]);
    });
}
function registerLocaleInStandaloneApp(mainFile, options) {
    const locale = options.locale || 'en_US';
    return (0, schematics_2.chain)([
        (host) => __awaiter(this, void 0, void 0, function* () {
            try {
                const bootstrapCall = (0, util_1.findBootstrapApplicationCall)(host, mainFile);
                if (!bootstrapCall) {
                    console.log();
                    console.log((0, chalk_1.yellow)(`Could not find bootstrap application call in file (${(0, chalk_1.blue)(mainFile)}).`));
                    return void 0;
                }
                const appConfig = (0, app_config_1.findAppConfig)(bootstrapCall, host, mainFile);
                if (!appConfig || !appConfig.filePath) {
                    console.log();
                    console.log((0, chalk_1.yellow)(`Could not find app config in file (${(0, chalk_1.blue)(mainFile)}).`));
                    return void 0;
                }
                const appConfigFile = appConfig.filePath;
                const appConfigSource = (0, schematics_1.parseSourceFile)(host, appConfig.filePath);
                if (!appConfigSource) {
                    console.log();
                    console.log((0, chalk_1.yellow)(`Could not parse app config file (${(0, chalk_1.blue)(appConfigFile)}).`));
                    return void 0;
                }
                const localePrefix = locale.split('_')[0];
                (0, apply_changes_1.applyChangesToFile)(host, appConfigFile, [
                    safeInsertImport(appConfigSource, appConfigFile, locale, 'ng-zorro-antd/i18n'),
                    safeInsertImport(appConfigSource, appConfigFile, 'registerLocaleData', '@angular/common'),
                    safeInsertImport(appConfigSource, appConfigFile, localePrefix, `@angular/common/locales/${localePrefix}`, true),
                    registerLocaleData(appConfigSource, appConfigFile, localePrefix)
                ]);
            }
            catch (e) {
                console.log((0, chalk_1.yellow)(`Error registering locale in standalone app: ${e.message}`));
            }
        }),
        (0, utility_1.addRootProvider)(options.project, ({ code, external }) => {
            return code `${external('provideNzI18n', 'ng-zorro-antd/i18n')}(${locale})`;
        })
    ]);
}
function registerLocaleData(moduleSource, modulePath, locale) {
    const allImports = (0, schematics_1.findNodes)(moduleSource, ts.SyntaxKind.ImportDeclaration);
    const allFun = (0, schematics_1.findNodes)(moduleSource, ts.SyntaxKind.ExpressionStatement);
    // Check if allImports is valid before proceeding
    if (!allImports || allImports.length === 0) {
        console.log((0, chalk_1.yellow)(`Could not add the registerLocaleData to file (${(0, chalk_1.blue)(modulePath)}).` +
            `because no import declarations were found.`));
        console.log((0, chalk_1.yellow)(`Please manually add the following code:`));
        console.log((0, chalk_1.cyan)(`registerLocaleData(${locale});`));
        return new change_1.NoopChange();
    }
    // Safely filter the expression statements
    const registerLocaleDataFun = allFun.filter(node => {
        if (!node)
            return false;
        const children = node.getChildren();
        if (!children || children.length === 0) {
            return false;
        }
        const firstChild = children[0];
        if (!firstChild) {
            return false;
        }
        const firstChildChildren = firstChild.getChildren();
        if (!firstChildChildren || firstChildChildren.length === 0) {
            return false;
        }
        const firstChildFirstChild = firstChildChildren[0];
        if (!firstChildFirstChild) {
            return false;
        }
        return firstChildFirstChild.getText() === 'registerLocaleData';
    });
    if (registerLocaleDataFun.length === 0) {
        return (0, schematics_1.insertAfterLastOccurrence)(allImports, `\n\nregisterLocaleData(${locale});`, modulePath, 0);
    }
    else {
        console.log((0, chalk_1.yellow)(`Could not add the registerLocaleData to file (${(0, chalk_1.blue)(modulePath)}).` +
            `because there is already a registerLocaleData function.`));
        console.log((0, chalk_1.yellow)(`Please manually add the following code:`));
        console.log((0, chalk_1.cyan)(`registerLocaleData(${locale});`));
        return new change_1.NoopChange();
    }
}
function insertI18nTokenProvide(moduleSource, modulePath, locale) {
    const metadataField = 'providers';
    const nodes = (0, schematics_1.getDecoratorMetadata)(moduleSource, 'NgModule', '@angular/core');
    // Check if nodes are valid
    if (!nodes || nodes.length === 0) {
        console.log((0, chalk_1.yellow)(`Could not find NgModule decorator in file (${(0, chalk_1.blue)(modulePath)}).`));
        console.log((0, chalk_1.yellow)(`Please manually add the following code to your providers:`));
        console.log((0, chalk_1.cyan)(`provideNzI18n(${locale})`));
        return [];
    }
    const addProvide = (0, schematics_1.addSymbolToNgModuleMetadata)(moduleSource, modulePath, 'providers', `provideNzI18n(${locale})`, null);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const node = nodes[0];
    if (!node) {
        return [];
    }
    // Check if a node has properties
    if (!node.properties) {
        console.log((0, chalk_1.yellow)(`Could not find properties in NgModule decorator in file (${(0, chalk_1.blue)(modulePath)}).`));
        console.log((0, chalk_1.yellow)(`Please manually add the following code to your providers:`));
        console.log((0, chalk_1.cyan)(`provideNzI18n(${locale})`));
        return [];
    }
    const matchingProperties = node.properties
        .filter(prop => prop && prop.kind === ts.SyntaxKind.PropertyAssignment)
        .filter((prop) => {
        if (!prop || !prop.name)
            return false;
        const name = prop.name;
        switch (name.kind) {
            case ts.SyntaxKind.Identifier:
                return name.getText(moduleSource) === metadataField;
            case ts.SyntaxKind.StringLiteral:
                return name.text === metadataField;
        }
        return false;
    });
    if (!matchingProperties) {
        return [];
    }
    if (matchingProperties.length) {
        const assignment = matchingProperties[0];
        if (!assignment || !assignment.initializer || assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
            return [];
        }
        const arrLiteral = assignment.initializer;
        if (!arrLiteral.elements || arrLiteral.elements.length === 0) {
            return addProvide;
        }
        else {
            // Safely check for getText method before calling it
            const provideWithToken = arrLiteral.elements.some(e => e && typeof e.getText === 'function' && e.getText().includes('NZ_I18N'));
            const provideWithFunc = arrLiteral.elements.some(e => e && typeof e.getText === 'function' && e.getText().includes('provideNzI18n'));
            if (!provideWithFunc && !provideWithToken) {
                return addProvide;
            }
            console.log();
            console.log((0, chalk_1.yellow)(`Could not provide the locale token to file (${(0, chalk_1.blue)(modulePath)}), because there is already a locale token in providers.`));
            if (provideWithToken) {
                console.log((0, chalk_1.yellow)(`Please manually add the following code to your providers:`));
                console.log((0, chalk_1.cyan)(`provideNzI18n(${locale})`));
            }
            return [];
        }
    }
    else {
        return addProvide;
    }
}
//# sourceMappingURL=register-locale.js.map