import { toParse } from "../common/base";
import { Basic, BasicOpt } from "../common/basic";
import global from "./global";

export interface DeviceOpt extends BasicOpt {
  SDK: any;
}

export class Device extends Basic {
  sdk: any;
  BridgeEventName = "GameMsg"; // 通路事件名

  constructor(opt: DeviceOpt) {
    super(opt);
    this.sdk = opt.SDK; // 暂存sdk
    global.init(opt.SDK); // 初始化全局事件监听
  }

  /**
   * 初始化监听全局消息
   */
  init(callback: any) {
    return global.on(this.BridgeEventName, (data: ReqMessage) => {
      this.logger.log("get BridgeEventName info", data);
      const info: ReqMessage = JSON.parse(JSON.stringify(data));
      if (info && info.payload) {
        // payload.params 为JSON字符串数组，统一解析
        const { params } = info.payload;
        if (params && params.length) {
          info.payload.params = params.map((param) =>
            toParse(param, undefined)
          );
        }
        callback && callback(info);
      }
    });
  }

  /**
   * 销毁消息监听
   */
  destroy() {
    return global.off(this.BridgeEventName);
  }

  /**
   * 发送消息
   */
  emit(data: RspMessage | EmitMessage) {
    this.logger.log("emit msg", data);
    return global.emit(this.BridgeEventName, data);
  }
}
