"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ComponentsRunner = void 0;
const child_process_1 = require("child_process");
class ComponentsRunner {
    constructor({ logger, path }) {
        this.running = false;
        this.run = () => {
            this.stop();
            this.write('Starting component build...');
            this.running = true;
            const installPackageProcess = this.installPackages();
            installPackageProcess.on('exit', (code) => {
                if (code === 0) {
                    this.buildComponents();
                }
                else {
                    this.running = false;
                    this.write(`Failed to build packages.\nExited with code ${code}`);
                }
            });
            return this.wait();
        };
        this.stop = () => {
            if (this.process) {
                this.write('Stopping component build...');
                this.process.kill(9);
            }
        };
        this.wait = (ms = 2000) => {
            return new Promise((resolve) => {
                const interval = setInterval(() => {
                    if (!this.running) {
                        resolve();
                        clearInterval(interval);
                    }
                }, ms);
            });
        };
        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.buildComponents = () => {
            this.process = (0, child_process_1.spawn)('yarn', ['build'], {
                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('exit', (code) => {
                if (code !== 0) {
                    this.write(`Failed to build packages.\nExited with code ${code}`);
                }
                this.running = false;
            });
        };
        this.write = (msg) => {
            this.logger.add(msg.replace(/\n$/, ''));
        };
        this.logger = logger;
        this.path = path;
    }
}
exports.ComponentsRunner = ComponentsRunner;
//# sourceMappingURL=componentsRunner.js.map