"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const events_1 = require("events");
/**
 * A Child Process which automatically logs all output to the console
 */
class ManagedChildProcess extends events_1.EventEmitter {
    constructor(name, command, args, cwd, detached) {
        super();
        this.name = name;
        this.command = command;
        this.args = args;
        this.cwd = cwd;
        this.detached = detached;
    }
    /** Spawn process and keep track of its output */
    spawn() {
        if (this.process) {
            throw Error('You must not spawn the same ManagedChildProcess multiple times.');
        }
        this.process = child_process_1.spawn(this.command, this.args, { cwd: this.cwd, detached: this.detached });
        this.logContent(`has been started`);
        // Add event listeners to process
        this.process.stdout.on('data', (data) => {
            // @BUG: This is only shows after the user presses CTRL+C.
            //       It does not show it any other circumstances.
            this.logContent(data.toString('utf8'));
        });
        this.process.stderr.on('data', (data) => {
            this.logContent(data.toString('utf8'));
        });
        this.process.on('exit', (code, signal) => {
            if (code) {
                this.logContent(`exited with code ${code}`);
            }
            else {
                this.logContent(`exited with signal ${signal}`);
            }
            this.process = undefined;
        });
    }
    /** Politely ask the child process to exit */
    kill() {
        if (this.process) {
            this.process.kill();
        }
    }
    logContent(content) {
        this.emit('output', {
            source: this.name,
            content: removeTrailingNewlines(content),
        });
    }
}
exports.ManagedChildProcess = ManagedChildProcess;
/** Remove all newlines at the end of a string */
function removeTrailingNewlines(str) {
    let newString = str;
    while (newString.endsWith('\n')) {
        newString = newString.substr(0, newString.length - 1);
    }
    return newString;
}
//# sourceMappingURL=ManagedChildProcess.js.map