import { EventEmitter } from "events";
import { toParse, toString } from "../common/base";


type OnGameMessage = {
  callback: (res: { name: string, message: string }) => void
}

type OffGameMessage = {
  callback?: (res: { name: string, message: string }) => void
}

/**
 * 全局唯一监听桥接
 */
class Global {
  sdk: any;
  _bus: EventEmitter;
  _mainEvent = "MainGameEvent";
  _mainBus: EventEmitter;

  constructor() {
    this._bus = new EventEmitter();
    this._mainBus = new EventEmitter();
  }

  init(sdk: any) {
    if (!sdk || this.sdk) return;
    this.sdk = sdk;
    return this.sdk.exe.onGameMessage({
      callback: (res: any) => {
        const { name, message } = res;
        this._bus.emit(name, toParse(message));
        this._mainBus.emit(this._mainEvent, res);
      },
    });
  }

  destroy() {
    return this.sdk.exe.offGameMessage();
  }

  onGameMessage(params: OnGameMessage) {
    this._mainBus.addListener(this._mainEvent, params.callback);
  }

  offGameMessage(params?: OffGameMessage) {
    if (params?.callback) {
      this._mainBus.removeListener(this._mainEvent, params.callback);
    } else {
      this._mainBus.removeAllListeners(this._mainEvent);
    }
  }

  sendToGame(message: any) {
    return this.sdk.exe.sendToGame({ message });
  }

  on(name: string, callback: any) {
    this._bus.addListener(name, callback);
  }

  off(name: string, callback?: any) {
    if (callback) {
      this._bus.removeListener(name, callback);
    } else {
      this._bus.removeAllListeners(name);
    }
  }

  emit(name: string, message: any) {
    return this.sdk.exe.sendToGame({
      message: toString({ name, message }),
    });
  }
}

export default new Global();
