"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const chalk_1 = require("chalk");
const child_process_1 = require("child_process");
const npm_1 = require("../server/npm");
const util_1 = require("../server/util");
const writer_1 = require("./writer");
function ensurePackagesInstalled(project, ...reqs) {
    return __awaiter(this, void 0, void 0, function* () {
        if (yield npm_1.isPackagedInstalled(project.baseDir(), ...reqs)) {
            return;
        }
        let config;
        try {
            config = yield project.packageJson();
        }
        catch (e) {
            writer_1.default.write("We couldn't read the package.json in your project directory:");
            throw e;
        }
        const doInstall = yield writer_1.default.confirm('To do this, we first need to install some dependencies. This may take a minute or two.');
        if (!doInstall) {
            writer_1.default.write(chalk_1.default.red('Installation aborted'));
            process.exit(0);
        }
        const areAllRequired = !reqs.some(r => {
            const isRequired = (config.dependencies && config.dependencies[r]) ||
                (config.devDependencies && config.devDependencies[r]);
            return !isRequired;
        });
        writer_1.default.write('Installing packages:', reqs);
        let proc;
        if (areAllRequired) {
            proc = child_process_1.spawn('npm', ['install'], { cwd: project.baseDir() });
        }
        else {
            proc = child_process_1.spawn('npm', ['install', '--save-dev'].concat(reqs), { cwd: project.baseDir() });
        }
        return util_1.awaitChildProcess(proc);
    });
}
/**
 * Ensures that webpack and the webpack-dev-server are installed in the
 * target directory, installing them if they aren't.
 */
function ensureWebpackDependencies(project) {
    return __awaiter(this, void 0, void 0, function* () {
        return ensurePackagesInstalled(project, 'webpack', 'webpack-dev-server');
    });
}
exports.ensureWebpackDependencies = ensureWebpackDependencies;
