"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.deviceManager = void 0;
const enum_1 = require("@debug-server-next/@types/enum");
const log_1 = require("@debug-server-next/utils/log");
const db_1 = require("@debug-server-next/db");
const debug_target_1 = require("@debug-server-next/utils/debug-target");
const config_1 = require("@debug-server-next/config");
const app_client_manager_1 = require("@debug-server-next/client/app-client-manager");
const pub_sub_manager_1 = require("@debug-server-next/controller/pub-sub-manager");
const report_1 = require("@debug-server-next/utils/report");
const log = new log_1.TunnelLogger('device-manager');
class DeviceManager {
    constructor() {
        this.deviceList = [];
    }
    /**
     * app disconnection, clean debugTarget
     */
    onAppDisconnect() {
        const device = this.deviceList[0];
        if (!device)
            return;
        // 通过 tunnel 通道创建的 debugTarget 的 clientId 为 devicename
        (0, pub_sub_manager_1.cleanDebugTarget)(device.devicename, false);
    }
    /**
     * app connection, add debugTarget and subscribe upward protocol
     */
    async onAppConnect() {
        log.verbose('app connect, %j', this.deviceList);
        const device = this.deviceList[0];
        if (!device)
            return log.warn('no device connect!');
        const useTunnel = app_client_manager_1.appClientManager.shouldUseAppClientType(device.platform, "TunnelAppClient" /* AppClientType.Tunnel */);
        log.verbose('useTunnel %j, is connected %j', useTunnel, device.physicalstatus === "1" /* DeviceStatus.Connected */);
        if (device.physicalstatus === "1" /* DeviceStatus.Connected */ && useTunnel) {
            try {
                let debugTarget = (0, debug_target_1.createTargetByDeviceInfo)(device);
                debugTarget = await (0, debug_target_1.patchDebugTarget)(debugTarget);
                const { DB } = (0, db_1.getDBOperator)();
                log.verbose('before upsert db %j', debugTarget);
                new DB(config_1.config.redis.debugTargetTable).upsert(debugTarget.clientId, debugTarget);
                (0, pub_sub_manager_1.subscribeCommand)(debugTarget);
                report_1.report.event({
                    name: enum_1.ReportEvent.RemoteDebug,
                    ext1: debugTarget.title,
                    ext2: debugTarget.platform,
                });
            }
            catch (e) {
                log.error('app connect e, %j, %j', e === null || e === void 0 ? void 0 : e.stack, e);
            }
        }
    }
    async getDeviceList() {
        global.addon.getDeviceList((devices) => {
            log.verbose('getDeviceList: %j', devices);
            this.deviceList = devices;
            if (devices.length) {
                const isDeviceDisconnect = devices[0].physicalstatus === "2" /* DeviceStatus.Disconnected */;
                if (isDeviceDisconnect)
                    return;
                // TODO tunnel doesn't support multiple device, so just select the first one
                const device = this.deviceList[0];
                const deviceId = device.deviceid;
                log.verbose(`selectDevice ${deviceId}`);
                global.addon.selectDevice(deviceId);
            }
        });
    }
}
exports.deviceManager = new DeviceManager();
