"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClientRunner = void 0;
const child_process_1 = require("child_process");
const open_1 = __importDefault(require("open"));
class ClientRunner {
    constructor({ logger, path, port, clientUrl }) {
        this.start = () => {
            this.stop();
            this.write('Starting client runner...');
            const installPackageProcess = this.installPackages();
            installPackageProcess.on('exit', (code) => {
                if (code === 0) {
                    this.startClient();
                }
                else {
                    this.write(`Failed to install packges.\nExited with code ${code}`);
                }
            });
        };
        this.stop = () => {
            if (this.process) {
                this.write('Stopping client runner...');
                this.process.kill(9);
            }
        };
        this.installPackages = () => {
            this.process = (0, child_process_1.spawn)('yarn', ['--force', '--prefer-offline'], {
                cwd: this.path,
            });
            this.process.stdout.on('data', (msg) => {
                this.write(msg.toString());
            });
            this.process.stderr.on('data', (msg) => {
                this.write(msg.toString());
            });
            return this.process;
        };
        this.startClient = () => {
            this.process = (0, child_process_1.spawn)('env', ['BROWSER=none', `PORT=${this.port}`, 'yarn', 'start'], {
                cwd: this.path,
            });
            this.process.stdout.on('data', (msg) => {
                this.write(msg.toString());
            });
            this.process.stderr.on('data', (msg) => {
                this.write(msg.toString());
            });
            this.process.on('spawn', () => (0, open_1.default)(this.clientUrl));
        };
        this.write = (msg) => {
            this.logger.add(msg.replace(/\n$/, ''));
        };
        this.logger = logger;
        this.path = path;
        this.port = port;
        this.clientUrl = clientUrl;
    }
}
exports.ClientRunner = ClientRunner;
//# sourceMappingURL=clientRunner.js.map