"use strict";
/*
 * Tencent is pleased to support the open source community by making
 * Hippy available.
 *
 * Copyright (C) 2017-2019 THL A29 Limited, a Tencent company.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.patchIOSTarget = exports.getIWDPPages = void 0;
const tslib_1 = require("tslib");
const request_promise_1 = tslib_1.__importDefault(require("request-promise"));
const lodash_1 = require("lodash");
const enum_1 = require("@debug-server-next/@types/enum");
const config_1 = require("@debug-server-next/config");
const url_1 = require("@debug-server-next/utils/url");
const log_1 = require("@debug-server-next/utils/log");
const timer_1 = require("@debug-server-next/utils/timer");
const debug_target_1 = require("@debug-server-next/utils/debug-target");
const log = new log_1.Logger('IWDP-util');
/**
 * get all IWDP pages of connected iOS device
 */
const getIWDPPages = async (iWDPPort) => {
    if (config_1.config.isCluster)
        return [];
    try {
        // IWDP detect page maybe slow, do some sleep
        await (0, timer_1.sleep)(800);
        const deviceList = await (0, request_promise_1.default)({
            url: '/json',
            baseUrl: `http://127.0.0.1:${iWDPPort}`,
            json: true,
        });
        const debugTargets = (await Promise.all(deviceList.map(getDeviceIWDPPages))) || [];
        return debugTargets.flat().filter(iWDPPagesFilter);
    }
    catch (e) {
        return [];
    }
};
exports.getIWDPPages = getIWDPPages;
/**
 * use IWDP info extend debugTarget
 */
const patchIOSTarget = (debugTarget, iOSPages) => {
    if (debugTarget.platform !== enum_1.DevicePlatform.IOS)
        return debugTarget;
    const iOSPage = findIOSPage(debugTarget, iOSPages);
    if (!iOSPage) {
        const i = debugTarget.appClientTypeList.indexOf("IWDPAppClient" /* AppClientType.IWDP */);
        if (i !== -1)
            debugTarget.appClientTypeList.splice(i, 1);
        delete debugTarget.deviceOSVersion;
        delete debugTarget.deviceId;
        delete debugTarget.deviceOSVersion;
        return debugTarget;
    }
    iOSPage.shouldRemove = true;
    const iWDPWsUrl = iOSPage.webSocketDebuggerUrl;
    const wsUrl = (0, url_1.makeUrl)(`${config_1.config.wsDomain}${config_1.config.wsPath}`, {
        clientId: debugTarget.clientId,
        role: enum_1.ClientRole.Devtools,
    });
    const devtoolsFrontendUrl = (0, url_1.makeUrl)(`${config_1.config.domain}/front_end/inspector.html`, {
        remoteFrontend: true,
        experiments: true,
        ws: (0, debug_target_1.wsUrlWithoutProtocol)(wsUrl),
        env: global.debugAppArgv.env,
    });
    const { appClientTypeList } = debugTarget;
    if (appClientTypeList.indexOf("IWDPAppClient" /* AppClientType.IWDP */) === -1)
        appClientTypeList.push("IWDPAppClient" /* AppClientType.IWDP */);
    return {
        ...debugTarget,
        iWDPWsUrl,
        appClientTypeList,
        deviceName: iOSPage.device.deviceName,
        deviceId: iOSPage.device.deviceId,
        deviceOSVersion: iOSPage.device.deviceOSVersion,
        title: iOSPage.title,
        devtoolsFrontendUrl,
        webSocketDebuggerUrl: wsUrl,
    };
};
exports.patchIOSTarget = patchIOSTarget;
/**
 * get IWDP pages of one device
 */
const getDeviceIWDPPages = async (device) => {
    const port = device.url.match(/:(\d+)/)[1];
    try {
        const targets = await (0, request_promise_1.default)({
            url: '/json',
            baseUrl: `http://127.0.0.1:${port}`,
            json: true,
        });
        targets.forEach((target) => (target.device = device));
        return targets;
    }
    catch (e) {
        log.error('getDeviceIWDPPages error, %s', e === null || e === void 0 ? void 0 : e.stack);
        return [];
    }
};
const iWDPPagesFilter = (iWDPPage) => /^HippyContext/.test(iWDPPage.title) && !/\(delete\)/.test(iWDPPage.title);
//  && Boolean(iWDPPage.devtoolsFrontendUrl);
const findIOSPage = (debugTarget, iOSPages) => {
    const iOSPagesWithFlag = iOSPages;
    // should use last created JSContext
    return (0, lodash_1.findLast)(iOSPagesWithFlag, (iOSPage) => 
    /**
     * TODO doesn't support multiple device with same title
     * this will cause updating debugTargets deviceInfo confused in list page
     */
    (debugTarget.appClientTypeList.includes("WSAppClient" /* AppClientType.WS */) && debugTarget.title === iOSPage.title) ||
        // && debugTarget.deviceName === iOSPage.device.deviceName
        (debugTarget.appClientTypeList.includes("TunnelAppClient" /* AppClientType.Tunnel */) &&
            debugTarget.deviceName === iOSPage.device.deviceName));
};
