"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.IWDPAppClient = void 0;
const tslib_1 = require("tslib");
const ws_1 = tslib_1.__importDefault(require("ws"));
const enum_1 = require("@debug-server-next/@types/enum");
const log_1 = require("@debug-server-next/utils/log");
const app_client_1 = require("./app-client");
const log = new log_1.Logger('app-client:IWDP', enum_1.WinstonColor.BrightBlue);
/**
 * Communicate with app by IWDP
 */
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(enum_1.WSCode.AppClientDestroyed, 'IWDPAppClient is destroyed');
    }
    registerMessageListener() {
        if (!this.ws)
            return;
        this.ws.on('message', async (msg) => {
            const msgStr = msg.toString();
            let msgObj;
            try {
                msgObj = JSON.parse(msgStr);
                const res = await 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.verbose(`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.emit("close" /* AppClientEvent.Close */);
            log.verbose('IWDPAppClient ws close!');
        });
        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,
                });
            }
        });
    }
    /**
     * connect to IWDP server
     */
    connect() {
        var _a, _b;
        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', e === null || e === void 0 ? void 0 : e.stack);
            throw e;
        }
    }
    startPing() {
        this.pingTimer = setInterval(() => {
            this.ws.ping('ping');
        }, 1000);
    }
    stopPing() {
        this.pingTimer && clearInterval(this.pingTimer);
    }
}
exports.IWDPAppClient = IWDPAppClient;
