"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addAndinstallDependencies = void 0;
const tasks_1 = require("@angular-devkit/schematics/tasks");
const getOptionsKeys_1 = require("./helpers/getOptionsKeys");
function sortObjectByKeys(obj) {
    return Object.keys(obj)
        .sort()
        .reduce((result, key) => {
        result[key] = obj[key];
        return result;
    }, {});
}
const addPackageToPackageJson = (host, _options, _context) => {
    if (host.exists("package.json") == false) {
        host.create("package.json", "{}");
    }
    const sourceText = host.read("package.json").toString("utf-8");
    const json = JSON.parse(sourceText);
    if (!json.dependencies) {
        json.dependencies = {};
    }
    let toInstallKeys = (0, getOptionsKeys_1.getOptionskeys)(_options, _context);
    for (const installKey of toInstallKeys) {
        if (installKey.deps !== undefined) {
            Object.keys(installKey.deps).forEach((key) => {
                if (!json.dependencies[key]) {
                    json.dependencies[key] = installKey.deps[key];
                }
            });
        }
    }
    json.dependencies = sortObjectByKeys(json.dependencies);
    host.overwrite("package.json", JSON.stringify(json, null, 2));
    return host;
};
const addPackageToDevPackageJson = (host, _options, _context) => {
    if (host.exists("package.json") == false) {
        host.create("package.json", "{}");
    }
    const sourceText = host.read("package.json").toString("utf-8");
    const json = JSON.parse(sourceText);
    if (!json.devDependencies) {
        json.devDependencies = {};
    }
    let toInstallKeys = (0, getOptionsKeys_1.getOptionskeys)(_options, _context);
    for (const installKey of toInstallKeys) {
        if (installKey.devDeps !== undefined) {
            Object.keys(installKey.devDeps).forEach((key) => {
                if (!json.devDependencies[key]) {
                    json.devDependencies[key] = installKey.devDeps[key];
                }
            });
        }
    }
    host.overwrite("package.json", JSON.stringify(json, null, 2));
    return host;
};
const addAndinstallDependencies = (_options) => {
    return (tree, _context) => {
        addPackageToDevPackageJson(tree, _options, _context);
        addPackageToPackageJson(tree, _options, _context);
        if (_options.skipInstall == false) {
            _context.addTask(new tasks_1.NodePackageInstallTask());
            _context.logger.debug("✅️ Dependencies installed");
        }
        return tree;
    };
};
exports.addAndinstallDependencies = addAndinstallDependencies;
//# sourceMappingURL=addAndInstallDependencies.js.map