"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.subscribeOnToolEvents = void 0;
const os_1 = __importDefault(require("os"));
const p_queue_1 = __importDefault(require("p-queue"));
const constants_1 = require("../constants");
const plugin_utils_1 = require("../../plugin-utils");
const create_workers_1 = require("../../workers/create-workers");
const server_utils_1 = require("../../server-utils");
const constants_2 = require("../../constants");
const testplane_1 = require("../../test-adapter/testplane");
const subscribeOnToolEvents = (testplane, reportBuilder, client) => {
    const queue = new p_queue_1.default({ concurrency: os_1.default.cpus().length });
    testplane.on(testplane.events.RUNNER_START, (runner) => {
        reportBuilder.registerWorkers((0, create_workers_1.createWorkers)(runner));
    });
    testplane.on(testplane.events.SUITE_BEGIN, (suite) => {
        if (suite.pending) {
            return;
        }
        client.emit(constants_1.ClientEvents.BEGIN_SUITE, {
            suiteId: (0, plugin_utils_1.getSuitePath)(suite).join(' '),
            status: constants_2.TestStatus.RUNNING
        });
    });
    [
        { eventName: testplane.events.TEST_BEGIN, clientEventName: constants_1.ClientEvents.BEGIN_STATE },
        { eventName: testplane.events.TEST_PASS, clientEventName: constants_1.ClientEvents.TEST_RESULT },
        { eventName: testplane.events.RETRY, clientEventName: constants_1.ClientEvents.TEST_RESULT },
        { eventName: testplane.events.TEST_FAIL, clientEventName: constants_1.ClientEvents.TEST_RESULT },
        { eventName: testplane.events.TEST_PENDING, clientEventName: constants_1.ClientEvents.TEST_RESULT }
    ].forEach(({ eventName, clientEventName }) => {
        testplane.on(eventName, (data) => {
            queue.add(async () => {
                const status = (0, testplane_1.getStatus)(eventName, testplane.events, data);
                const formattedResultWithoutAttempt = (0, server_utils_1.formatTestResult)(data, status);
                const formattedResult = await reportBuilder.addTestResult(formattedResultWithoutAttempt);
                const testBranch = reportBuilder.getTestBranch(formattedResult.id);
                return client.emit(clientEventName, testBranch);
            }).catch(server_utils_1.logError);
        });
    });
    testplane.on(testplane.events.RUNNER_END, async () => {
        try {
            await queue.onIdle();
            client.emit(constants_1.ClientEvents.END);
        }
        catch (err) {
            (0, server_utils_1.logError)(err);
        }
    });
};
exports.subscribeOnToolEvents = subscribeOnToolEvents;
//# sourceMappingURL=report-subscriber.js.map