"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 });
const core_1 = require("@angular-devkit/core");
const schematics_1 = require("@angular-devkit/schematics");
const package_handler_1 = require("../utils/package-handler");
const dependency_handler_1 = require("../utils/dependency-handler");
const add_normalize_1 = require("./add-normalize");
const util_1 = require("../utils/util");
const enablePolyfills = (tree, context) => __awaiter(void 0, void 0, void 0, function* () {
    const project = yield util_1.getDefaultProject(tree);
    const targetFile = dependency_handler_1.getConfigFile(project, 'polyfills', context);
    if (!tree.exists(targetFile)) {
        context.logger.warn(`${targetFile} not found. You may need to update polyfills.ts manually.`);
        return;
    }
    // Match all commented import statements that are core-js/es6/*
    const pattern = /\/{2}\s{0,}(import\s{0,}\'core\-js\/es6\/.+)/;
    let polyfillsData = tree.read(targetFile).toString();
    if (pattern.test(polyfillsData)) {
        let result;
        // eslint-disable-next-line no-cond-assign
        while (result = pattern.exec(polyfillsData)) {
            polyfillsData = polyfillsData.replace(result[0], result[1]);
        }
    }
    return polyfillsData;
});
const enableWebAnimationsAndGridSupport = (tree, targetFile, polyfillsData) => {
    // Target the web-animations-js commented import statement and uncomment it.
    const webAnimationsLine = '// import \'web-animations-js\';';
    polyfillsData = polyfillsData.replace(webAnimationsLine, webAnimationsLine.substring(3, webAnimationsLine.length));
    tree.overwrite(targetFile, polyfillsData);
};
const readInput = (options) => (tree, context) => __awaiter(void 0, void 0, void 0, function* () {
    const workspaceHost = util_1.createHost(tree);
    const { workspace } = yield core_1.workspaces.readWorkspace(tree.root.path, workspaceHost);
    if (options.polyfills) {
        const targetProperty = 'es5BrowserSupport';
        const project = workspace.projects.get(workspace.extensions['defaultProject']);
        const polyfillsFile = dependency_handler_1.getConfigFile(project, 'polyfills', context);
        if (polyfillsFile !== undefined) {
            const build = project.targets.get('build');
            let polyfillsData = tree.read(polyfillsFile).toString();
            if (build.options[targetProperty] !== undefined) {
                // If project targets angular cli version >= 7.3
                build.options[targetProperty] = true;
                enableWebAnimationsAndGridSupport(tree, polyfillsFile, polyfillsData);
                yield core_1.workspaces.writeWorkspace(workspace, workspaceHost);
            }
            else {
                // If project targets angular cli version < 7.3
                polyfillsData = yield enablePolyfills(tree, context);
                enableWebAnimationsAndGridSupport(tree, polyfillsFile, polyfillsData);
            }
        }
        else {
            context.logger.warn(`You may want to manually uncomment '// import 'web-animations-js' in polyfills.ts`);
        }
    }
});
const addNormalize = (options) => (tree, context) => __awaiter(void 0, void 0, void 0, function* () {
    if (options.resetCss) {
        const workspaceHost = util_1.createHost(tree);
        const { workspace } = yield core_1.workspaces.readWorkspace(tree.root.path, util_1.createHost(tree));
        const result = add_normalize_1.addResetCss(workspace, tree);
        yield core_1.workspaces.writeWorkspace(workspace, workspaceHost);
        if (!result) {
            context.logger.warn(`Could not complete adding reset styles. Those may need to be added manually.`);
        }
    }
});
exports.default = (options) => schematics_1.chain([
    readInput(options),
    addNormalize(options),
    dependency_handler_1.addDependencies(options),
    package_handler_1.installPackageJsonDependencies(options),
    dependency_handler_1.logSuccess(options)
]);
