"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCmd = void 0;
const https_1 = require("https");
const crypto_1 = require("crypto");
const logger_1 = require("@applitools/logger");
const ufg_client_1 = require("@applitools/ufg-client");
const utils_1 = require("./utils");
const eyes_1 = require("./eyes");
const utils = __importStar(require("@applitools/utils"));
const node_fetch_1 = __importDefault(require("node-fetch"));
const value = new TextEncoder().encode(JSON.stringify({ resources: {}, domNodes: [] }));
const hash = (0, crypto_1.createHash)('sha256').update(value).digest('hex');
const contentType = 'x-applitools-html/cdt';
const resource = {
    id: 'id',
    url: 'https://localhost:2107',
    value,
    hash: { hashFormat: 'sha256', hash, contentType },
    contentType,
};
const UFG_PUT_RESOURCE_URL = `https://render-wus.applitools.com/sha256/${resource.hash.hash}?render-id=fake`;
const accessTokenPromise = new Promise(async (resolve) => {
    const { stdout } = await utils.process.execute(`curl -s ${eyes_1.RENDER_INFO_URL} ${(0, utils_1.getProxyCurlArg)()}`, {
        maxBuffer: 10000000,
    });
    const accessToken = JSON.parse(stdout).accessToken;
    if (!accessToken)
        throw new Error('could not receive auth token since cURL command to get it failed.');
    resolve(accessToken);
});
const getCmd = async () => `curl -X PUT -H "Content-Type: application/json" -H "X-Auth-Token: ${await accessTokenPromise}" -d '${resource.value}' ${UFG_PUT_RESOURCE_URL} ${(0, utils_1.getProxyCurlArg)()}`;
exports.getCmd = getCmd;
const validateVgResult = (res, sha) => {
    if (!res || res.hash !== sha) {
        throw new Error(`bad VG result ${res}`);
    }
};
exports.default = {
    async testFetch() {
        const response = await (0, node_fetch_1.default)(UFG_PUT_RESOURCE_URL, {
            method: 'PUT',
            headers: {
                'Content-Type': 'x-applitools-html/cdt',
                'X-Auth-Token': await accessTokenPromise,
            },
            body: resource.value,
        });
        const data = await response.json();
        validateVgResult(data, resource.hash.hash);
    },
    async testCurl() {
        // HTTP_PROXY and HTTPS_PROXY are read by cURL.
        let proxyUrl;
        if (utils_1.config.proxy) {
            proxyUrl = new URL(utils.types.isString(utils_1.config.proxy) ? utils_1.config.proxy : utils_1.config.proxy.url);
            if (utils_1.config.proxy.username)
                proxyUrl.username = utils_1.config.proxy.username;
            if (utils_1.config.proxy.password)
                proxyUrl.password = utils_1.config.proxy.password;
        }
        const { stdout } = await utils.process.execute(await (0, exports.getCmd)(), { maxBuffer: 10000000 });
        validateVgResult(JSON.parse(stdout), resource.hash.hash);
    },
    testServer: async () => {
        const url = new URL(UFG_PUT_RESOURCE_URL);
        const requests = (0, ufg_client_1.makeUFGRequests)({
            settings: { ufgServerUrl: url.origin, accessToken: await accessTokenPromise },
            logger: (0, logger_1.makeLogger)(),
        });
        await requests.uploadResource({ resource });
    },
    async testHttps() {
        return new Promise(async (resolve, reject) => {
            const url = new URL(UFG_PUT_RESOURCE_URL);
            const request = (0, https_1.request)({
                host: url.host,
                path: `${url.pathname}${url.search}`,
                method: 'PUT',
                headers: {
                    'Content-Type': 'x-applitools-html/cdt',
                    'X-Auth-Token': await accessTokenPromise,
                },
            });
            request.on('response', response => {
                let data = '';
                response.on('data', chunk => (data += chunk));
                response.on('end', () => {
                    try {
                        validateVgResult(JSON.parse(data), resource.hash.hash);
                        resolve();
                    }
                    catch (e) {
                        reject(e);
                    }
                });
            });
            request.on('error', reject);
            request.write(resource.value);
            request.end();
        });
    },
    url: new URL(UFG_PUT_RESOURCE_URL),
    getCmd: exports.getCmd,
};
