"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
exports.addImportOnly = addImportOnly;
exports.addProviderToAppModule = addProviderToAppModule;
exports.addProviderToModuleProvider = addProviderToModuleProvider;
exports.updateAppConfigFile = updateAppConfigFile;
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 ast_utils_1 = require("@schematics/angular/utility/ast-utils");
const changes_1 = require("./changes");
const module_1 = require("@po-ui/ng-schematics/module");
const ng_ast_utils_1 = require("@schematics/angular/utility/ng-ast-utils");
const readline = require("readline");
const IconsDictionaryName = 'ICONS_DICTIONARY';
const poIconDictionary = 'PoIconDictionary';
const poModuleSourcePath = '@po-ui/ng-components';
const newProviderDictionary = `
    {
      provide: 'ICONS_DICTIONARY',
      useValue: 'PoIconDictionary'
    }`;
function askQuestion(query) {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    return new Promise(resolve => rl.question(query, (answer) => {
        rl.close();
        resolve(answer);
    }));
}
function main(options) {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const configureNewIcon = yield askQuestion('A Lib de ícones PO Icon está depreciada e será removida na versão 20, gostaria de usar a nova lib?(yes/no)');
        if (configureNewIcon.toLowerCase() === 'yes' ||
            configureNewIcon.toLowerCase() === 'y' ||
            configureNewIcon.toLowerCase() === 'sim' ||
            configureNewIcon.toLowerCase() === '') {
            return (0, schematics_1.chain)([(0, package_config_1.updatePackageJson)('21.7.0', changes_1.updateDepedenciesVersion), createUpgradeRule(), postUpdate()]);
        }
        else {
            return (0, schematics_1.chain)([
                (0, package_config_1.updatePackageJson)('21.7.0', changes_1.updateDepedenciesVersion),
                addImportOnly(options, [IconsDictionaryName, poIconDictionary], poModuleSourcePath),
                addProviderToAppModule(options, newProviderDictionary),
                updateAppConfigFileRule(),
                postUpdate()
            ]);
        }
    });
}
function default_1(options) {
    return (_tree, _context) => main(options);
}
function addImportOnly(_, moduleNames, importPath) {
    return (host) => {
        var _a;
        const workspace = (_a = (0, project_1.getWorkspaceConfigGracefully)(host)) !== null && _a !== void 0 ? _a : {};
        const projectNames = Object.keys(workspace.projects);
        for (const projectName of projectNames) {
            const project = (0, project_1.getProjectFromWorkspace)(workspace, projectName);
            const browserEntryPoint = (0, project_1.getProjectMainFile)(project);
            if ((0, ng_ast_utils_1.isStandaloneApp)(host, browserEntryPoint)) {
                return host;
            }
            const modulePath = (0, ng_ast_utils_1.getAppModulePath)(host, browserEntryPoint);
            let importStatement;
            if (Array.isArray(moduleNames)) {
                const names = moduleNames.join(', ');
                importStatement = `import { ${names} } from '${importPath}';\n`;
            }
            else {
                importStatement = `import { ${moduleNames} } from '${importPath}';\n`;
            }
            const recorder = host.beginUpdate(modulePath);
            recorder.insertLeft(0, importStatement);
            host.commitUpdate(recorder);
        }
        return host;
    };
}
function addProviderToAppModule(_, provider) {
    return (host) => {
        var _a;
        const workspace = (_a = (0, project_1.getWorkspaceConfigGracefully)(host)) !== null && _a !== void 0 ? _a : {};
        const projectNames = Object.keys(workspace.projects);
        for (const projectName of projectNames) {
            const project = (0, project_1.getProjectFromWorkspace)(workspace, projectName);
            const browserEntryPoint = (0, project_1.getProjectMainFile)(project);
            if ((0, ng_ast_utils_1.isStandaloneApp)(host, browserEntryPoint)) {
                return host;
            }
            const appModulePath = (0, ng_ast_utils_1.getAppModulePath)(host, browserEntryPoint);
            addProviderToModuleProvider(host, appModulePath, provider);
        }
        return host;
    };
}
// para inserir variáveis no provider
function addProviderToModuleProvider(tree, modulePath, provider) {
    const moduleSource = (0, module_1.getSourceFile)(tree, modulePath);
    const changes = (0, ast_utils_1.addProviderToModule)(moduleSource, modulePath, `
    ${provider}`, null);
    return insertChanges(tree, changes, modulePath);
}
function insertChanges(tree, changes, modulePath) {
    const recorder = tree.beginUpdate(modulePath);
    changes.forEach(change => {
        if (change) {
            recorder.insertLeft(change.pos, change.toAdd);
        }
    });
    tree.commitUpdate(recorder);
}
function updateAppConfigFileRule() {
    return (tree) => {
        var _a, _b;
        const workspace = (_a = (0, project_1.getWorkspaceConfigGracefully)(tree)) !== null && _a !== void 0 ? _a : {};
        const projectNames = Object.keys(workspace.projects);
        for (const projectName of projectNames) {
            const project = (0, project_1.getProjectFromWorkspace)(workspace, projectName);
            const browserEntryPoint = (0, project_1.getProjectMainFile)(project);
            if (!(0, ng_ast_utils_1.isStandaloneApp)(tree, browserEntryPoint)) {
                return tree;
            }
            const content = ((_b = tree.read('src/app/app.config.ts')) === null || _b === void 0 ? void 0 : _b.toString('utf-8')) || '';
            const conteudoModificado = updateAppConfigFile(content);
            tree.overwrite('src/app/app.config.ts', conteudoModificado);
        }
        return tree;
    };
}
function updateAppConfigFile(content) {
    const newImports = `import { ICONS_DICTIONARY, PoIconDictionary } from '@po-ui/ng-components';`;
    const newProvider = `
    {
      provide: ICONS_DICTIONARY,
      useValue: PoIconDictionary
    },`;
    // Verificar se já existe o import e o provider
    const importExists = content.includes(newImports);
    const providerExists = content.includes(newProvider.trim());
    let modifiedContent = content;
    if (!importExists) {
        // Adiciona o novo import
        modifiedContent = modifiedContent.replace(/import { ApplicationConfig,[^}]+} from '@angular\/core';/, match => `${match}\n${newImports}`);
    }
    if (!providerExists) {
        // Adiciona o novo provider
        modifiedContent = modifiedContent.replace(/providers: \[[^\]]+\]/, match => match.replace('providers: [', `providers: [${newProvider}`));
    }
    return modifiedContent.trim();
}
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);
                    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: `$1ph ${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