"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IWDPAppClient = void 0;
const tslib_1 = require("tslib");
const ws_1 = tslib_1.__importDefault(require("ws"));
const enum_1 = require("@/@types/enum");
const log_1 = require("@/utils/log");
const app_client_1 = require("./app-client");
const log = new log_1.Logger('app-client:IWDP', enum_1.WinstonColor.BrightBlue);
/**
 * IWDP 调试通道，通过 ws client 与 IWDP server 建立连接
 */
class IWDPAppClient extends app_client_1.AppClient {
    constructor(id, option) {
        super(id, option);
        this.requestPromiseMap = new Map();
        this.isConnecting = false;
        this.msgBuffer = [];
        this.url = option.iWDPWsUrl;
        if (!this.url) {
            const e = new Error('IWDPAppClient constructor option need iWDPWsUrl, if you are debug iOS without USB, please ignore this error.');
            throw e;
        }
        this.connect();
    }
    destroy() {
        var _a;
        if (((_a = this.ws) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.OPEN)
            this.ws.close();
    }
    registerMessageListener() {
        if (!this.ws)
            return;
        this.ws.on('message', (msg) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            let msgObj;
            try {
                msgObj = JSON.parse(msg);
                const res = yield this.downwardMessageHandler(msgObj);
                if (!('id' in msgObj))
                    return;
                const requestPromise = this.requestPromiseMap.get(msgObj.id);
                if (requestPromise) {
                    requestPromise.resolve(res);
                }
            }
            catch (e) {
                log.error(`IWDPAppClient parse json error: ${msg}`);
            }
        }));
        this.ws.on('open', () => {
            this.isConnecting = false;
            this.startPing();
            log.info(`IWDPAppClient ws opened: ${this.url}`);
            for (const { msg, resolve, reject } of this.msgBuffer) {
                const msgStr = JSON.stringify(msg);
                this.ws.send(msgStr);
                this.requestPromiseMap.set(msg.id, { resolve, reject });
            }
            this.msgBuffer = [];
        });
        this.ws.on('close', () => {
            this.stopPing();
            this.isConnecting = false;
            this.isClosed = true;
            this.emit("close" /* Close */);
            log.warn('IWDPAppClient ws close!');
            const e = new Error('IWDPAppClient ws closed');
            for (const requestPromise of this.requestPromiseMap.values()) {
                requestPromise.reject(e);
            }
        });
        this.ws.on('error', (e) => {
            this.stopPing();
            this.isConnecting = false;
            log.error('IWDPAppClient ws error: %s', e === null || e === void 0 ? void 0 : e.stack);
        });
    }
    sendHandler(msg) {
        return new Promise((resolve, reject) => {
            var _a;
            if (((_a = this.ws) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.OPEN) {
                const msgStr = JSON.stringify(msg);
                this.ws.send(msgStr);
                this.requestPromiseMap.set(msg.id, { resolve, reject });
            }
            else {
                if (!this.isConnecting) {
                    this.connect();
                    this.isConnecting = true;
                }
                this.msgBuffer.push({
                    msg,
                    resolve,
                    reject,
                });
            }
        });
    }
    /**
     * 与 IWDP server 建立连接
     */
    connect() {
        var _a, _b, _c;
        if (((_a = this.ws) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.OPEN || ((_b = this.ws) === null || _b === void 0 ? void 0 : _b.readyState) === ws_1.default.CONNECTING)
            return;
        try {
            this.ws = new ws_1.default(this.url);
            this.registerMessageListener();
        }
        catch (e) {
            log.error('IWDP connect error: %s', (_c = e) === null || _c === void 0 ? void 0 : _c.stack);
            throw e;
        }
    }
    startPing() {
        this.pingTimer = setInterval(() => {
            this.ws.ping('ping');
        }, 1000);
    }
    stopPing() {
        this.pingTimer && clearInterval(this.pingTimer);
    }
}
exports.IWDPAppClient = IWDPAppClient;
