"use strict";
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.replaceFdWithBtp = replaceFdWithBtp;
const schematics_1 = require("@angular-devkit/schematics");
const schematics_2 = require("@angular/cdk/schematics");
const path_1 = require("path");
const one_time_packages_1 = require("../utils/one-time-packages");
const workspace_1 = require("../utils/workspace");
const get_file_dependencies_1 = require("./get-file-dependencies");
const replacements_1 = require("./replacements");
const exportedElements = new Set([
    'SplitterPaginationComponent',
    'SplitterPaneContainerComponent',
    'NoDefaultPanePipe',
    'transformPaneTypeInput',
    'PaneType',
    'PaneTypeInput',
    'SplitterResizerComponent',
    'SplitterSplitPaneComponent',
    'SplitterComponent',
    'SplitterModule',
    'SplitterPaneResizeEvent',
    'SplitterPaneContainerOrientation',
    'SplitterPaneContainerOrientationType'
]);
const replaceRegex = (content) => {
    for (const [regex, replacement] of replacements_1.regexReplacements.entries()) {
        content = content.replace(regex, replacement);
    }
    return content;
};
/**
 * Migrates the project to the new splitter component.
 * @param options
 */
function replaceFdWithBtp({ project: projectName }) {
    const [install, uninstall] = (0, one_time_packages_1.oneTimePackages)(['@swc/core', 'dependency-tree']);
    return (0, schematics_1.chain)([
        install,
        (tree) => __awaiter(this, void 0, void 0, function* () {
            const { parseSync, printSync } = yield Promise.resolve().then(() => require('@swc/core'));
            const project = yield (0, workspace_1.getProjectDefinition)(tree, projectName);
            const mainFile = (0, schematics_2.getProjectMainFile)(project);
            const projectBuildTargetName = yield (0, workspace_1.getProjectBuildTargetName)(tree, projectName);
            const tsConfigPath = (0, schematics_2.getTargetTsconfigPath)(project, projectBuildTargetName);
            const tsFilesList = (yield (0, get_file_dependencies_1.getFileDependencies)(mainFile, tsConfigPath)).map((p) => p.replace(process.cwd(), '.'));
            tsFilesList.forEach((filePath) => {
                const originalContent = tree.readText(filePath);
                let newContent = replaceRegex(originalContent);
                const parsed = parseSync(newContent, {
                    syntax: 'typescript',
                    decorators: true
                });
                let replaced = false;
                parsed.body.forEach((node, index) => {
                    var _a;
                    if (node.type === 'ImportDeclaration' && node.source.value === '@fundamental-ngx/core') {
                        const specifiers = node.specifiers.filter((specifier) => specifier.type === 'ImportSpecifier' && exportedElements.has(specifier.local.value));
                        if (specifiers.length) {
                            const newImport = Object.assign({}, node);
                            newImport.specifiers = specifiers;
                            newImport.source = {
                                type: 'StringLiteral',
                                value: '@fundamental-ngx/btp/splitter',
                                span: node.source.span
                            };
                            node.specifiers = node.specifiers.filter((s) => !specifiers.includes(s));
                            parsed.body.splice(index, node.specifiers.length === 0 ? 1 : 0, newImport);
                            replaced = true;
                        }
                        return;
                    }
                    const classDeclaration = (() => {
                        if (node.type === 'ClassDeclaration') {
                            return node;
                        }
                        if (node.type === 'ExportDeclaration' && node.declaration.type === 'ClassDeclaration') {
                            return node.declaration;
                        }
                        return undefined;
                    })();
                    if (classDeclaration) {
                        const componentDecorator = (_a = classDeclaration.decorators) === null || _a === void 0 ? void 0 : _a.find((decorator) => decorator.expression.type === 'CallExpression' &&
                            decorator.expression.callee.type === 'Identifier' &&
                            decorator.expression.callee.value === 'Component');
                        if (componentDecorator) {
                            const objectExpression = componentDecorator.expression.type === 'CallExpression'
                                ? componentDecorator.expression.arguments[0]
                                : undefined;
                            if ((objectExpression === null || objectExpression === void 0 ? void 0 : objectExpression.expression.type) === 'ObjectExpression') {
                                const templateUrlProperty = objectExpression === null || objectExpression === void 0 ? void 0 : objectExpression.expression.properties.find((prop) => prop.type === 'KeyValueProperty' &&
                                    prop.key.type === 'Identifier' &&
                                    prop.key.value === 'templateUrl');
                                const templateUrlPropertyValue = (templateUrlProperty === null || templateUrlProperty === void 0 ? void 0 : templateUrlProperty.type) === 'KeyValueProperty' &&
                                    (templateUrlProperty === null || templateUrlProperty === void 0 ? void 0 : templateUrlProperty.value.type) === 'StringLiteral'
                                    ? templateUrlProperty.value.value
                                    : undefined;
                                if (templateUrlPropertyValue) {
                                    const pathToFile = (0, path_1.resolve)((0, path_1.dirname)(filePath), templateUrlPropertyValue).replace(process.cwd(), '.');
                                    const originalFile = tree.readText(pathToFile);
                                    const newFile = replaceRegex(originalFile);
                                    if (originalFile !== newFile) {
                                        tree.overwrite(pathToFile, newFile);
                                    }
                                }
                            }
                        }
                    }
                });
                if (replaced) {
                    newContent = printSync(parsed).code;
                }
                if (newContent !== originalContent) {
                    tree.overwrite(filePath, newContent);
                }
            });
        }),
        uninstall
    ]);
}
//# sourceMappingURL=replace-fd-with-btp.js.map