"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebSocketClass = void 0;
exports.getOptionalConnectDevice = getOptionalConnectDevice;
exports.handleListenMsgEvent = handleListenMsgEvent;
var index_1 = require("./index");
var ws_1 = __importDefault(require("ws"));
var os_1 = __importDefault(require("os"));
var fs_1 = __importDefault(require("fs"));
function getOptionalConnectDevice(connectDeviceArr) {
    var result = {};
    connectDeviceArr.map(function (item) {
        var clientId = item.clientId, type = item.type, name = item.name, status = item.status;
        if (type === 'debug' && status === 'online') {
            result[name] = clientId;
        }
    });
    return result;
}
function handleListenMsgEvent(msgEventName, data) {
    var _a, _b, _c;
    switch (msgEventName) {
        case 'sysEventPush':
            if (typeof data === 'string') {
                index_1.logger.info(data);
            }
            else if (typeof data === 'object' && ((_a = data === null || data === void 0 ? void 0 : data.params) === null || _a === void 0 ? void 0 : _a.clients)) {
                var connectedDevice = getOptionalConnectDevice(data.params.clients);
                process.env._bridgeOptionalDevice = JSON.stringify(connectedDevice);
            }
            break;
        case 'connectClient':
            var _d = data.result, result = _d === void 0 ? '' : _d, _e = data.error, error = _e === void 0 ? {} : _e;
            if (result && result === 'success') {
                var choiredDevice = process.env._bridgeChoiredDevice;
                index_1.logger.info("successfully connected to ".concat(choiredDevice, "."));
            }
            if (error && JSON.stringify(error) !== '{}') {
                var _f = data.error, _g = _f.code, code = _g === void 0 ? 0 : _g, _h = _f.message, message = _h === void 0 ? '' : _h;
                index_1.logger.error("".concat(code, ": ").concat(message));
            }
            break;
        case 'sysSettingPush':
            if (typeof data === 'string') {
                index_1.logger.info(data);
            }
            else if (typeof data === 'object' && ((_b = data === null || data === void 0 ? void 0 : data.params) === null || _b === void 0 ? void 0 : _b.content)) {
                index_1.logger.info(data.params.content);
            }
            break;
        case 'sysMessagePush':
            if (typeof data === 'string') {
                index_1.logger.info(data);
            }
            else if (typeof data === 'object' && ((_c = data === null || data === void 0 ? void 0 : data.params) === null || _c === void 0 ? void 0 : _c.content)) {
                index_1.logger.info(data.params.content);
            }
            break;
        case 'logPush':
            if (typeof data === 'string') {
                index_1.logger.info(data);
            }
            else if (typeof data === 'object' && (data === null || data === void 0 ? void 0 : data.params)) {
                var _j = data.params, _k = _j.level, level = _k === void 0 ? 'DEBUG' : _k, _l = _j.time, time = _l === void 0 ? new Date().getTime() : _l, message = _j.message;
                var timeString = time.toString();
                var fTime = Number(timeString.length > 13 ? timeString.substr(0, 13) : timeString);
                var str = "[".concat(level.toUpperCase(), "-").concat(new Date(fTime).toLocaleTimeString(), ".").concat(new Date(fTime).getMilliseconds(), "] ").concat(message);
                index_1.logger.info(str);
            }
            break;
        case 'screenShot':
            var path_1 = "".concat(os_1.default.homedir(), "/desktop/screenShot.png");
            fs_1.default.writeFile(path_1, Buffer.from(data.result, 'hex'), function (err) {
                if (err) {
                    index_1.logger.log('screenShot error', err);
                }
                else {
                    index_1.logger.success("screenShot path:".concat(path_1));
                }
            });
            break;
        default:
            break;
    }
}
var WebSocketClass = (function () {
    function WebSocketClass(_a) {
        var url = _a.url, connectWSCB = _a.connectWSCB, disConnectWSCB = _a.disConnectWSCB;
        var _this = this;
        this.msgEventIDs = {};
        this.handleListenMsgEventReturn = function (data) {
            var message = data.toString('utf8');
            var me = _this;
            if (message.includes('{')) {
                message = JSON.parse(message);
            }
            else if (message === 'ping') {
                me.sendMessage('pong');
                return;
            }
            var _a = message || {}, _b = _a.method, method = _b === void 0 ? '' : _b, _c = _a.id, id = _c === void 0 ? 0 : _c;
            Object.keys(_this.msgEventIDs).forEach(function (item) {
                if (message && !method && _this.msgEventIDs[item] === id) {
                    method = item;
                }
            });
            try {
                handleListenMsgEvent(method, message);
            }
            catch (error) {
                index_1.logger.error("handleListenMsgEvent, ".concat(JSON.stringify(error)));
            }
        };
        this.socket = new ws_1.default(url);
        this.socket.on('open', function () {
            connectWSCB();
            _this.listenEvent();
        });
        this.socket.on('close', function () {
            disConnectWSCB();
        });
        this.socket.on('error', function (error) {
            index_1.logger.error(error);
        });
    }
    WebSocketClass.prototype.sendMessage = function (params, options) {
        if (options === void 0) { options = {}; }
        var msgParams;
        var msg = params;
        var _a = options.method, method = _a === void 0 ? '' : _a;
        if (method) {
            msgParams = {
                method: method,
                params: params,
                jsonrpc: '2.0',
                id: this.createMsgEventID(method, params === null || params === void 0 ? void 0 : params.type),
            };
            msg = JSON.stringify(msgParams);
        }
        this.socket.send(msg, { binary: false });
    };
    WebSocketClass.prototype.createMsgEventID = function (method, type) {
        var id = parseInt('' + Math.random() * 10000);
        var prop = method;
        var typeMap = {
            screenshot: 'screenShot',
        };
        if (type && typeMap[type]) {
            prop = typeMap[type];
        }
        this.msgEventIDs[prop] = id;
        return id;
    };
    WebSocketClass.prototype.listenEvent = function () {
        var _this = this;
        this.socket.on('message', function (data) {
            _this.handleListenMsgEventReturn(data);
        });
    };
    return WebSocketClass;
}());
exports.WebSocketClass = WebSocketClass;
