"use strict";
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const http_1 = require("http");
const finalhandler_1 = __importDefault(require("finalhandler"));
const serve_static_1 = __importDefault(require("serve-static"));
const intercept_stdout_1 = __importDefault(require("intercept-stdout"));
const AU = require("ansi_up");
const ansiUp = new AU.default();
ansiUp.use_classes = true;
ansiUp.escape_for_html = false;
const operators_1 = require("rxjs/operators");
exports.default = {
    name: "pilot",
    aliases: ["server", "web", "s", "w"],
    isVisible: false,
    flags: {
        port: {
            aliases: ["p"],
        },
    },
    run: ({ flags, request, feature, config, utils }) => {
        const chalk = utils.color();
        const { "@slo/slo-plugin-pilot": pilotConfig } = config, allConfig = __rest(config, ["@slo/slo-plugin-pilot"]);
        const { name, version, bin } = feature.package;
        const defaultPilotConfig = {
            appName: name || "Dashboard",
            docTitle: name || "Dashboard",
            appVersion: version || "0.0",
            cmdName: Object.keys(bin)[0],
        };
        const socket = feature.socket.startServer().init({
            requestRunCommand: request.runCommand,
            requestAllCommands: () => ({
                onRequestAllCommands: request.getCommands(),
            }),
            requestConfig: () => ({
                onRequestConfig: Object.assign({ pilot: Object.assign(Object.assign({}, defaultPilotConfig), pilotConfig) }, allConfig),
            }),
        });
        intercept_stdout_1.default((txt) => {
            socket.sendMessage({
                type: "log",
                message: ansiUp.ansi_to_html(txt),
            });
        }, (err) => {
            socket.sendMessage({
                type: "log",
                message: ansiUp.ansi_to_html(err),
            });
        });
        if (feature.promptConfig) {
            feature.promptConfig.customPrompt = (questions) => {
                socket.sendMessage({ questions, messageId: 123 });
                return new Promise((res) => {
                    socket
                        .listen()
                        .pipe(operators_1.take(1), operators_1.filter((data) => data.REQUEST === "answers"), operators_1.map((a) => a.PAYLOAD), operators_1.filter((data) => data.qid === 123), operators_1.map((a) => a.ans))
                        .subscribe(a => res(a));
                });
            };
        }
        const dir = path_1.resolve(__dirname, "../public");
        const serve = serve_static_1.default(dir, { index: ["index.html"] });
        const server = http_1.createServer((req, res) => {
            serve(req, res, finalhandler_1.default(req, res));
        });
        server.listen(flags.port || 3000);
        console.log(`${chalk.green("Pilot")} ${chalk.gray("Server started... ")}`);
        console.log(`${chalk.green("Pilot")} ${chalk.gray(`Running at ${chalk.blue.bold(`http://localhost:${flags.port || 3000}`)}`)}`);
    },
};
