"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
const tslib_1 = require("tslib");
const schematics_1 = require("@angular-devkit/schematics");
const tasks_1 = require("@angular-devkit/schematics/tasks");
const package_config_1 = require("@po-ui/ng-schematics/package-config");
const project_1 = require("@po-ui/ng-schematics/project");
const changes_1 = require("./changes");
function main() {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        return (0, schematics_1.chain)([(0, package_config_1.updatePackageJson)('21.17.0', changes_1.updateDepedenciesVersion), createUpgradeRule(), postUpdate()]);
    });
}
function default_1() {
    return (_tree, _context) => main();
}
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 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}`;
            applyUpdateInContent(tree, sourceDir);
        }
    };
}
function applyUpdateInContent(tree, path) {
    const directory = tree.getDir(path);
    // Função recursiva para processar arquivos e subdiretórios
    const processDirectory = (dir) => {
        // Processa todos os arquivos no diretório atual
        if (dir.subfiles.length) {
            dir.subfiles.forEach((file) => {
                const filePath = dir.path + '/' + file;
                const content = tree.read(filePath).toString('utf-8');
                if (!content) {
                    return;
                }
                let updated = content;
                if (file.endsWith('.html') || file.endsWith('.ts')) {
                    // Atualiza para as instâncias dos novos ícones
                    updated = replaceWithChanges(changes_1.poIconInsideReplaces, updated);
                    updated = replaceWithChanges(changes_1.poIconReplaces, updated);
                    updated = replaceWithChanges(changes_1.phIconReplaces, updated);
                    updated = replaceWithChanges(changes_1.phIconHifenReplaces, updated);
                    const icons = changes_1.iconsReplaced.filter((icon) => updated.includes(icon.replace));
                    icons.forEach(icon => {
                        const regexChange = new RegExp('(class="\\s?)?' + icon.replace + '(\\s?)?(?="|>|\\s|$|\'|")', 'gmi');
                        if (icon.fill) {
                            updated = replaceWithChanges([{ replace: regexChange, replaceWith: `$1${icon.replaceWith}$2` }], updated);
                        }
                        else {
                            updated = replaceWithChanges([{ replace: regexChange, replaceWith: `$1an ${icon.replaceWith}$2` }], updated);
                        }
                    });
                    if (updated !== content) {
                        tree.overwrite(filePath, updated);
                    }
                }
            });
        }
        // Processa subdiretórios recursivamente
        if (dir.subdirs.length) {
            dir.subdirs.forEach((subdir) => {
                processDirectory(tree.getDir(dir.path + '/' + subdir));
            });
        }
    };
    // Inicia o processamento a partir do diretório especificado
    processDirectory(directory);
}
function replaceWithChanges(replaces, content = '') {
    replaces.forEach(({ replace, replaceWith }) => {
        const regex = new RegExp(replace, 'gi');
        content = content.replace(regex, replaceWith);
    });
    return content;
}
function postUpdate() {
    return (_, context) => {
        context.addTask(new tasks_1.NodePackageInstallTask());
    };
}
//# sourceMappingURL=index.js.map