"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 child_process_1 = require("child_process");
const http_1 = require("http");
const npm_1 = require("../../server/npm");
const server_1 = require("../../server/server");
const util_1 = require("../../server/util");
const webpack_plugin_1 = require("../../webpack-plugin");
const prereqs_1 = require("../prereqs");
const portfinder = require('portfinder');
portfinder.basePort = 13370;
function defaultArgs(original, defaults) {
    Object.keys(defaults).forEach(key => {
        if (original.some(arg => arg.startsWith(`--${key}`))) {
            return;
        }
        original = original.concat(`--${key}=${defaults[key]}`);
    });
    return original;
}
function default_1(options) {
    return __awaiter(this, void 0, void 0, function* () {
        yield prereqs_1.ensureWebpackDependencies(options.project);
        const argDelimiter = process.argv.indexOf('--');
        const port = yield portfinder.getPortPromise();
        const server = http_1.createServer(server_1.createApp(options.project)).listen(port);
        let args = argDelimiter > -1 ? process.argv.slice(argDelimiter + 1) : [];
        args = defaultArgs(args, {
            'content-base': 'src/',
            open: true,
        });
        server.on('listening', () => {
            const wds = npm_1.getPackageExecutable(options.project.baseDir('node_modules', 'webpack-dev-server'));
            const child = child_process_1.fork(wds, args, {
                cwd: process.cwd(),
                env: Object.assign({}, process.env, { [webpack_plugin_1.devEnvironmentVar]: JSON.stringify({
                        mixerAddress: options.api,
                        devServerAddress: `127.0.0.1:${server.address().port}`,
                    }) }),
            });
            child.on('close', code => {
                process.exit(code);
            });
        });
        return util_1.never();
    });
}
exports.default = default_1;
