"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslint_1 = require("tslint");
const tsquery_1 = require("@phenomnomnominal/tsquery");
const schematics_1 = require("@angular-devkit/schematics");
const ts_utils_1 = require("../ts-utils");
const utils_1 = require("../utils");
const angular_project_parser_1 = require("../angular-project-parser");
const mapped_imports_rule_utils_1 = require("../mapped-imports-rule-utils");
// TODO: add link to the docs
const conversionFailureMessage = `Failed to generate remapped imports! Please see: ...`;
function default_1(options) {
    return (tree, context) => {
        const { logger } = context;
        const filesToFix = getFilesToFix(tree, options.filesToIgnore);
        if (filesToFix.size === 0) {
            logger.debug('Convert Relative Imports: No files to fix.');
            return tree;
        }
        const tsConfigPath = angular_project_parser_1.getTsConfigFromProject(tree, options.project) || 'tsconfig.json';
        const compilerOptions = ts_utils_1.getCompilerOptions(tree, tsConfigPath);
        if (!compilerOptions) {
            logger.debug('Convert Relative Imports: Failed to parse the TS config file.');
            logger.error(conversionFailureMessage);
            return tree;
        }
        return fixImports(tree, logger, filesToFix, compilerOptions);
    };
}
exports.default = default_1;
function getFilesToFix(tree, filesToIgnore = []) {
    const isIgnoredFile = (f) => filesToIgnore.some((fileToIgnore) => fileToIgnore === f);
    const files = tree.actions.reduce((acc, action) => {
        const path = action.path.substr(1); // Remove the starting '/'.
        if (schematics_1.isContentAction(action) && path.endsWith('.ts') && !isIgnoredFile(path)) {
            acc.add(path);
        }
        return acc;
    }, new Set());
    return files;
}
function fixImports(tree, logger, filePaths, compilerOptions) {
    const rule = mapped_imports_rule_utils_1.getMappedImportsRule(compilerOptions);
    if (!rule) {
        logger.debug('Convert Relative Imports: Failed to extract remap options from the TS compiler options.');
        logger.error(conversionFailureMessage);
        return tree;
    }
    filePaths.forEach((path) => {
        const content = utils_1.getFileContents(tree, path);
        const fixedContent = applyTslintRuleFixes(rule, path, content);
        if (content !== fixedContent) {
            tree.overwrite(path, fixedContent);
        }
    });
    return tree;
}
function applyTslintRuleFixes(rule, filePath, fileContent) {
    const sourceFile = tsquery_1.tsquery.ast(fileContent, filePath);
    const ruleFailures = rule.apply(sourceFile);
    const fixes = ruleFailures.filter((error) => error.hasFix()).map((error) => error.getFix());
    const fixedContent = tslint_1.Replacement.applyFixes(fileContent, fixes);
    return fixedContent;
}
//# sourceMappingURL=index.js.map