"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeGenerator = void 0;
const req_1 = require("@applitools/req");
const utils = __importStar(require("@applitools/utils"));
async function* makeGenerator({ settings, logger, }) {
    var _a, _b;
    (_a = settings.pollingTimeout) !== null && _a !== void 0 ? _a : (settings.pollingTimeout = 10000);
    const req = (0, req_1.makeReq)({
        baseUrl: settings.pollingServerUrl,
        retry: {
            timeout: 10000,
            validate: ({ response, error }) => (response === null || response === void 0 ? void 0 : response.status) !== 200 &&
                !utils.types.instanceOf(error, 'AbortError') &&
                !utils.types.instanceOf(error, 'ConnectionTimeoutError'),
        },
        hooks: [handleLogs({ logger })],
        connectionTimeout: (_b = settings.timeout) !== null && _b !== void 0 ? _b : 5 * 60000,
    });
    const response = await req(`/tunnel-agents/${settings.agentId}/init`, {
        method: 'POST',
        headers: { 'x-secret': settings.secret },
        body: { instance_info: settings.envInfo },
    });
    const instanceId = await response.json().then((result) => result.instance_id);
    let pendingRequestMessages = [];
    let outgoingResponseMessages = [];
    let tunnelsEventMessage;
    let metricsEventMessage;
    while (true) {
        const response = await req(`/tunnel-agents/${settings.agentId}/agentpoll`, {
            method: 'POST',
            headers: { 'x-secret': settings.secret },
            body: {
                instance_id: instanceId,
                metrics: metricsEventMessage === null || metricsEventMessage === void 0 ? void 0 : metricsEventMessage.payload,
                open_tunnels: tunnelsEventMessage === null || tunnelsEventMessage === void 0 ? void 0 : tunnelsEventMessage.payload.map((tunnel) => ({ id: tunnel.tunnelId })),
                pending_tasks: pendingRequestMessages.map(message => ({ id: message.key })),
                completed_tasks: outgoingResponseMessages.map(message => {
                    if (message.payload.error) {
                        return {
                            id: message.key,
                            status: 'FAILED',
                            error: message.payload.error.message,
                            error_code: message.payload.reason,
                        };
                    }
                    else {
                        let response;
                        if (message.name === 'TunnelClient.create' || message.name === 'TunnelClient.replace') {
                            response = { tunnelId: message.payload.result.tunnelId };
                        }
                        else if (message.name === 'TunnelClient.fetch') {
                            response = { resource_content: message.payload.result };
                        }
                        return { id: message.key, status: 'SUCCESS', response };
                    }
                }),
                agent_status: 'OK',
            },
        });
        let incomingRequestMessages = [];
        let pollingTimeout = settings.pollingTimeout;
        try {
            const result = await response.json();
            if (result.abort) {
                return [{ name: 'TunnelClient.close', payload: { reason: result.abort_reason } }];
            }
            if (result.polling_interval_sec)
                pollingTimeout = result.polling_interval_sec * 1000;
            incomingRequestMessages = result.tasks.flatMap((task) => {
                if (task.type === 'CREATE_TUNNEL') {
                    return {
                        name: 'TunnelClient.create',
                        key: task.id,
                        payload: { apiKey: task.apiKey, eyesServerUrl: task.eyesServerUrl },
                    };
                }
                else if (task.type === 'DELETE_TUNNEL') {
                    return {
                        name: 'TunnelClient.destroy',
                        key: task.id,
                        payload: task.tunnel_id,
                    };
                }
                else if (task.type === 'REPLACE_TUNNEL') {
                    return {
                        name: 'TunnelClient.replace',
                        key: task.id,
                        payload: task.tunnel_id,
                    };
                }
                else if (task.type === 'GET_RESOURCE') {
                    return {
                        name: 'TunnelClient.fetch',
                        key: task.id,
                        payload: { resourceUrl: task.resource_url },
                    };
                }
                else {
                    return [];
                }
            });
        }
        catch (error) {
            logger.error(error);
            incomingRequestMessages = [];
        }
        pendingRequestMessages = pendingRequestMessages.concat(incomingRequestMessages);
        outgoingResponseMessages = [];
        const outgoingMessages = yield incomingRequestMessages;
        outgoingMessages.forEach(message => {
            if (message.name === 'TunnelClient.list')
                tunnelsEventMessage = message;
            else if (message.name === 'TunnelClient.metrics')
                metricsEventMessage = message;
            else
                outgoingResponseMessages.push(message);
        });
        pendingRequestMessages = pendingRequestMessages.filter(pendingMessage => !outgoingResponseMessages.some(outgoingMessage => outgoingMessage.key === pendingMessage.key));
        await utils.general.sleep(pollingTimeout);
    }
}
exports.makeGenerator = makeGenerator;
function handleLogs({ logger } = {}) {
    const guid = utils.general.guid();
    let counter = 0;
    return {
        beforeRequest({ request, options }) {
            let requestId = request.headers.get('x-applitools-eyes-client-request-id');
            if (!requestId) {
                requestId = `${counter++}--${guid}`;
                request.headers.set('x-applitools-eyes-client-request-id', requestId);
            }
            logger === null || logger === void 0 ? void 0 : logger.log(`Request [${requestId}] will be sent to the address "[${request.method}]${request.url}" with body`, options === null || options === void 0 ? void 0 : options.body);
        },
        beforeRetry({ request, attempt, error, response, options }) {
            const requestId = request.headers.get('x-applitools-eyes-client-request-id');
            logger === null || logger === void 0 ? void 0 : logger.log(`Request [${requestId}] that was sent to the address "[${request.method}]${request.url}" with body`, options === null || options === void 0 ? void 0 : options.body, `is going to retried due to ${error ? 'an error' : 'a response with status'}`, error !== null && error !== void 0 ? error : `${response.statusText}(${response.status})`);
            request.headers.set('x-applitools-eyes-client-request-id', `${requestId.split('#', 1)[0]}#${attempt + 1}`);
        },
        async afterResponse({ request, response }) {
            const requestId = request.headers.get('x-applitools-eyes-client-request-id');
            logger === null || logger === void 0 ? void 0 : logger.log(`Request [${requestId}] that was sent to the address "[${request.method}]${request.url}" respond with ${response.statusText}(${response.status})`, !response.ok ? `and body ${JSON.stringify(await response.clone().text())}` : '');
        },
        afterError({ request, error }) {
            const requestId = request.headers.get('x-applitools-eyes-client-request-id');
            logger === null || logger === void 0 ? void 0 : logger.error(`Request [${requestId}] that was sent to the address "[${request.method}]${request.url}" failed with error`, error);
        },
    };
}
