"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DebugTargetManager = void 0;
const tslib_1 = require("tslib");
const config_1 = require("@/config");
const iwdp_1 = require("@/utils/iwdp");
const debug_target_1 = require("@/utils/debug-target");
const db_1 = require("@/db");
const enum_1 = require("@/@types/enum");
const pub_sub_manager_1 = require("./pub-sub-manager");
class DebugTargetManager {
    /**
     * 根据 clientId 查询调试对象
     */
    static findDebugTarget(clientId, hash) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const debugTargets = yield DebugTargetManager.getDebugTargets(hash);
            return debugTargets.find((target) => target.clientId === clientId);
        });
    }
}
exports.DebugTargetManager = DebugTargetManager;
DebugTargetManager.debugTargets = [];
/**
 * 查询所有连接的调试对象
 */
DebugTargetManager.getDebugTargets = (hash) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    const { iWDPPort } = global.debugAppArgv;
    const { DB } = db_1.getDBOperator();
    const db = new DB(config_1.config.redis.debugTargetTable);
    let getDebugTargetPromise;
    if (config_1.config.isRemote) {
        getDebugTargetPromise = hash ? db.find('hash', hash) : Promise.resolve([]);
    }
    else {
        getDebugTargetPromise = db.getAll();
    }
    // TODO delete test code
    // getDebugTargetPromise = db.getAll();
    const [targets, iOSPages] = yield Promise.all([getDebugTargetPromise, iwdp_1.getIWDPPages(iWDPPort)]);
    targets.forEach((target, i) => {
        if (target.platform === enum_1.DevicePlatform.IOS) {
            targets[i] = iwdp_1.patchIOSTarget(target, iOSPages);
            pub_sub_manager_1.updateIWDPAppClient(targets[i]);
        }
    });
    // 追加 IWDP 获取到的 h5 页面
    const iOSPagesWithFlag = iOSPages;
    const h5Pages = iOSPagesWithFlag.filter((iOSPage) => !iOSPage.shouldRemove);
    const h5DebugTargets = h5Pages.map(debug_target_1.createTargetByIWDPPage);
    pub_sub_manager_1.subscribeByIWDP(h5DebugTargets);
    DebugTargetManager.debugTargets = targets.concat(h5DebugTargets);
    return DebugTargetManager.debugTargets;
});
