"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Thread = exports.ThreadType = void 0;
const worker_farm_1 = __importDefault(require("worker-farm"));
const env = __importStar(require("../environment"));
exports.ThreadType = {
    QUERY: "query",
    AUTOMATION: "automation",
};
function typeToFile(type) {
    let filename = null;
    switch (type) {
        case exports.ThreadType.QUERY:
            filename = "./query";
            break;
        case exports.ThreadType.AUTOMATION:
            filename = "./automation";
            break;
        default:
            throw "Unknown thread type";
    }
    return require.resolve(filename);
}
class Thread {
    constructor(type, opts = { timeoutMs: null, count: 1 }) {
        this.type = type;
        this.count = opts.count ? opts.count : 1;
        this.disableThreading =
            env.isTest() ||
                env.DISABLE_THREADING ||
                this.count === 0 ||
                env.isInThread();
        if (!this.disableThreading) {
            const workerOpts = {
                autoStart: true,
                maxConcurrentWorkers: this.count,
            };
            if (opts.timeoutMs) {
                this.timeoutMs = opts.timeoutMs;
                workerOpts.maxCallTime = opts.timeoutMs;
            }
            this.workers = (0, worker_farm_1.default)(workerOpts, typeToFile(type));
            Thread.workerRefs.push(this.workers);
        }
    }
    run(data) {
        return new Promise((resolve, reject) => {
            let fncToCall;
            // if in test then don't use threading
            if (this.disableThreading) {
                fncToCall = require(typeToFile(this.type));
            }
            else {
                fncToCall = this.workers;
            }
            fncToCall(data, (err, response) => {
                if (err && err.type === "TimeoutError") {
                    reject(new Error(`Query response time exceeded ${this.timeoutMs}ms timeout.`));
                }
                else if (err) {
                    reject(err);
                }
                else {
                    resolve(response);
                }
            });
        });
    }
    static stopThreads() {
        return new Promise(resolve => {
            if (Thread.workerRefs.length === 0) {
                resolve();
            }
            let count = 0;
            function complete() {
                count++;
                if (count >= Thread.workerRefs.length) {
                    resolve();
                }
            }
            for (let worker of Thread.workerRefs) {
                worker_farm_1.default.end(worker, complete);
            }
            Thread.workerRefs = [];
        });
    }
    static shutdown() {
        return __awaiter(this, void 0, void 0, function* () {
            yield Thread.stopThreads();
        });
    }
}
exports.Thread = Thread;
Thread.workerRefs = [];
