"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
const schematics_1 = require("@angular-devkit/schematics");
const tasks_1 = require("@angular-devkit/schematics/tasks");
const ng_ast_utils_1 = require("@schematics/angular/utility/ng-ast-utils");
const project_1 = require("@po-ui/ng-schematics/project");
const package_config_1 = require("@po-ui/ng-schematics/package-config");
const module_1 = require("@po-ui/ng-schematics/module");
const changes_1 = require("./changes");
const httpClientModuleName = 'HttpClientModule';
const httpClientModuleSourcePath = '@angular/common/http';
function default_1() {
    return (0, schematics_1.chain)([(0, package_config_1.updatePackageJson)('21.17.0', changes_1.updateDepedenciesVersion), createUpgradeRule(), postUpdate()]);
}
function postUpdate() {
    return (_, context) => {
        context.addTask(new tasks_1.NodePackageInstallTask());
    };
}
function createUpgradeRule() {
    return (tree, context) => {
        var _a;
        const logger = context.logger;
        const workspace = (_a = (0, project_1.getWorkspaceConfigGracefully)(tree)) !== null && _a !== void 0 ? _a : {};
        if (workspace === null) {
            logger.error('Não foi possível encontrar o arquivo de configuração de workspace.');
            return;
        }
        const themePathDefaultVariables = 'node_modules/@totvs/po-theme/css/po-theme-default-variables.min.css';
        const themePathDefaultMin = 'node_modules/@totvs/po-theme/css/po-theme-default.min.css';
        const themePathCore = 'node_modules/@po-ui/style/css/po-theme-core.min.css';
        const projectNames = Object.keys(workspace.projects);
        for (const projectName of projectNames) {
            const project = workspace.projects[projectName];
            const entryFolderProject = project.projectType === 'library' ? 'lib' : 'app';
            const sourceDir = `${project.sourceRoot}/${entryFolderProject}`;
            const appModulePath = (0, ng_ast_utils_1.getAppModulePath)(tree, (0, project_1.getProjectMainFile)(project));
            applyUpdateInContent(tree, sourceDir);
            //adiciona httpClientModule no app
            (0, module_1.addModuleImportToModule)(tree, appModulePath, httpClientModuleName, httpClientModuleSourcePath);
            //adiciona as variáveis no angular.json do theme-totvs
            addThemeStyleToTarget(project, 'build', tree, themePathDefaultVariables, workspace);
            addThemeStyleToTarget(project, 'test', tree, themePathDefaultVariables, workspace);
            addThemeStyleToTarget(project, 'build', tree, themePathDefaultMin, workspace);
            addThemeStyleToTarget(project, 'test', tree, themePathDefaultMin, workspace);
            addThemeStyleToTarget(project, 'build', tree, themePathCore, workspace);
            addThemeStyleToTarget(project, 'test', tree, themePathCore, workspace);
        }
    };
}
function applyUpdateInContent(tree, path) {
    const directory = tree.getDir(path);
    if (directory.subfiles.length) {
        directory.subfiles.forEach(file => {
            const filePath = path + '/' + file;
            // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
            const content = tree.read(filePath).toString('utf-8');
            if (!content) {
                return;
            }
            let updated = content;
            if (file.endsWith('.html')) {
                //utiliza o regex no html para atualização do po-button
                updated = replaceWithChanges(changes_1.poButtonReplacesSecondary, updated);
                updated = replaceWithChanges(changes_1.poButtonReplacesTertiary, updated);
                updated = replaceWithChanges(changes_1.poButtonReplacesDanger, updated);
                updated = replaceWithChanges(changes_1.poButtonReplaces, updated);
                if (updated !== content) {
                    tree.overwrite(filePath, updated);
                }
            }
        });
    }
    if (directory.subdirs.length) {
        directory.subdirs.forEach(subDir => {
            applyUpdateInContent(tree, path + '/' + subDir);
        });
    }
}
// Método usado para realizar alterações
function replaceWithChanges(replaces, content = '') {
    replaces.forEach(({ replace, replaceWith }) => {
        const regex = new RegExp(replace, 'gi');
        content = content.replace(regex, replaceWith);
    });
    return content;
}
function addThemeStyleToTarget(project, targetName, host, assetPath, workspace) {
    if (host.exists('package.json')) {
        // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
        const sourceText = host.read('package.json').toString('utf-8');
        const json = JSON.parse(sourceText);
        //só adiciona as novas dependencias do theme-totvs se o projeto tiver o theme-totvs instalado
        if (json.dependencies['@totvs/po-theme']) {
            const targetOptions = (0, project_1.getProjectTargetOptions)(project, targetName);
            if (!targetOptions.styles) {
                targetOptions.styles = [assetPath];
            }
            else {
                const existingStyles = targetOptions.styles.map((s) => (typeof s === 'string' ? s : s.input));
                for (const [, stylePath] of existingStyles.entries()) {
                    if (stylePath === assetPath) {
                        return;
                    }
                }
                targetOptions.styles.unshift(assetPath);
            }
            host.overwrite('angular.json', JSON.stringify(workspace, null, 2));
        }
    }
}
//# sourceMappingURL=index.js.map