"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.makeNMLRequests = void 0;
const req_broker_1 = require("./req-broker");
const utils = __importStar(require("@applitools/utils"));
const get_environments_info_1 = require("../utils/get-environments-info");
function makeNMLRequests({ settings, logger: mainLogger, }) {
    let brokerUrl = settings.brokerUrl;
    const supportedEnvironmentsUrl = settings.supportedEnvironmentsUrl;
    const proxy = settings.proxy;
    const req = (0, req_broker_1.makeReqBroker)({ settings, logger: mainLogger });
    return {
        preTakeScreenshot,
        takeScreenshots,
        takeSnapshots,
    };
    async function preTakeScreenshot({ logger = mainLogger } = {}) {
        var _a;
        logger = logger.extend(mainLogger, { tags: [`nml-request-${utils.general.shortid()}`] });
        logger.log('Request "preTakeScreenshot" called');
        const response = await req(brokerUrl, {
            name: 'PRE_TAKE_SCREENSHOT',
            body: {
                protocolVersion: '1.0',
                name: 'PRE_TAKE_SCREENSHOT',
                key: utils.general.guid(),
                payload: {},
            },
            logger,
        });
        const result = await response.json();
        if (((_a = result === null || result === void 0 ? void 0 : result.payload) === null || _a === void 0 ? void 0 : _a.result) === 'success')
            logger.log('Request "preTakeScreenshot" finished successfully with body', result.payload);
        else
            throw new Error(`There was a problem in pre take screenshot. The provided error message was "${result}"`);
        brokerUrl = result.nextPath;
    }
    async function takeScreenshots({ settings, logger = mainLogger, }) {
        var _a, _b;
        logger = logger.extend(mainLogger, { tags: [`nml-request-${utils.general.shortid()}`] });
        logger.log('Request "takeScreenshots" called with settings', settings);
        const { localEnvironment, renderEnvironments, environmentSettings } = await (0, get_environments_info_1.getNMLEnvironmentsInfo)({
            environments: settings.environments,
            supportedEnvironmentsUrl,
            proxy,
            logger,
        });
        try {
            const response = await req(brokerUrl, {
                name: 'TAKE_SCREENSHOT',
                body: {
                    protocolVersion: '1.0',
                    name: 'TAKE_SCREENSHOT',
                    key: utils.general.guid(),
                    payload: {
                        ...settings,
                        environments: undefined,
                        deviceList: !localEnvironment ? environmentSettings : undefined,
                        scrollRootElement: fallbackId(settings.scrollRootElement),
                        region: fallbackId(settings.region),
                        selectorsToFindRegionsFor: (_a = settings.selectorsToFindRegionsFor) === null || _a === void 0 ? void 0 : _a.map(selector => fallbackId(selector)),
                    },
                },
                logger,
            });
            const result = await response.json();
            brokerUrl = result.nextPath;
            let screenshots;
            if (Number(result.protocolVersion) >= 2) {
                logger.log(`Request "takeScreenshots" was performed on applitools lib v${result.nmlVersion} through protocol v${result.protocolVersion} on device`, result.payload.debugInfo);
                screenshots = localEnvironment
                    ? [
                        {
                            image: result.payload.result[0].result.screenshotUrl,
                            environment: localEnvironment,
                            calculateRegions: (_b = result.payload.result[0].result) === null || _b === void 0 ? void 0 : _b.selectorRegions,
                        },
                    ]
                    : renderEnvironments.map((environment, index) => {
                        var _a;
                        if (result.payload.result[index].error) {
                            throw new Error(`There was a problem in taking screenshot for environment ${JSON.stringify(environment)}. The provided error message was "${result.payload.result[index].error.message}" and had a stack trace of "${result.payload.result[index].error.stack}"`);
                        }
                        return {
                            image: result.payload.result[index].result.screenshotUrl,
                            calculateRegions: (_a = result.payload.result[index].result) === null || _a === void 0 ? void 0 : _a.selectorRegions,
                            environment,
                        };
                    });
            }
            else {
                screenshots = localEnvironment
                    ? [{ image: result.payload.result.screenshotUrl, environment: localEnvironment }]
                    : renderEnvironments.map((environment, index) => {
                        return { image: result.payload[index].result.screenshotUrl, environment };
                    });
            }
            logger.log('Request "takeScreenshots" finished successfully with body', screenshots);
            return screenshots;
        }
        catch (error) {
            if (error.nextPath)
                brokerUrl = error.nextPath;
            throw error;
        }
        function fallbackId(selector) {
            return utils.types.isString(selector) ? { type: 'accessibility-identifier', selector } : selector;
        }
    }
    async function takeSnapshots({ settings, logger = mainLogger, }) {
        try {
            const response = await req(brokerUrl, {
                name: 'TAKE_SNAPSHOT',
                body: {
                    protocolVersion: '1.0',
                    name: 'TAKE_SNAPSHOT',
                    key: utils.general.guid(),
                    payload: {
                        waitBeforeCapture: settings.waitBeforeCapture,
                    },
                },
                logger,
            });
            const result = await response.json();
            brokerUrl = result.nextPath;
            const platformName = result.payload.result.resourceMap.metadata.platformName;
            const snapshot = { platformName, vhsHash: result.payload.result.resourceMap.vhs };
            if (platformName === 'ios') {
                ;
                snapshot.vhsCompatibilityParams = {
                    UIKitLinkTimeVersionNumber: result.payload.result.metadata.UIKitLinkTimeVersionNumber,
                    UIKitRunTimeVersionNumber: result.payload.result.metadata.UIKitRunTimeVersionNumber,
                };
            }
            else if (platformName === 'android') {
                ;
                snapshot.vhsType = 'android-x';
            }
            return Array(settings.environments.length).fill(snapshot);
        }
        catch (error) {
            if (error.nextPath)
                brokerUrl = error.nextPath;
            throw error;
        }
    }
}
exports.makeNMLRequests = makeNMLRequests;
