"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getHttpAgent = getHttpAgent;
const agent_base_1 = require("agent-base");
const socks_proxy_agent_1 = require("socks-proxy-agent");
const MablHttpAgent_1 = require("./MablHttpAgent");
const RequestFilteringHttpAgent_1 = require("./RequestFilteringHttpAgent");
function getHttpAgent(shouldFilterHttpRequests, linkServers, proxyConfig, cookieJar) {
    const linkAgent = maybeGetSocksAgent(linkServers);
    if (linkAgent) {
        return MablHttpAgent_1.MablHttpAgent.createNewInstance({
            httpAgent: linkAgent,
            httpsAgent: linkAgent,
            cookieJar,
        });
    }
    else if (shouldFilterHttpRequests) {
        return RequestFilteringHttpAgent_1.RequestFilteringHttpAgent.createNewInstance({ cookieJar });
    }
    return MablHttpAgent_1.MablHttpAgent.createNewInstance({ proxyConfig, cookieJar });
}
function maybeGetSocksAgent(linkServers) {
    if (!linkServers?.length) {
        return;
    }
    const agentOptions = linkServers.map((linkServer) => ({
        host: linkServer.forwarding_host,
        port: linkServer.forwarding_port,
        userId: linkServer.workspace_id,
        password: linkServer.label,
        tls: {
            rejectUnauthorized: false,
        },
    }));
    if (agentOptions.length === 1) {
        return new socks_proxy_agent_1.SocksProxyAgent(agentOptions[0]);
    }
    return new MultiSocksProxyAgent(agentOptions);
}
class MultiSocksProxyAgent extends agent_base_1.Agent {
    constructor(options) {
        super();
        this.agents = options.map((proxy) => new socks_proxy_agent_1.SocksProxyAgent(proxy));
    }
    async callback(req, opts) {
        return this.selectAgent().callback(req, opts);
    }
    selectAgent() {
        return this.agents[Math.floor(Math.random() * this.agents.length)];
    }
    destroy() {
        this.agents.forEach((agent) => agent.destroy());
    }
}
