import baseUtil from '../../../utils/base';
import EventManager from '../../../manager/eventManager';
import tafManager from '../../../manager/tafManager';
import error from '../../../common/error';
import emitManager from './emitManager';
import prepareHUYA from './prepareHUYA';
import utils from './utils';
import TOPICS from '../const/topic';

const { DEV_MESSAGE } = TOPICS;

/**
 * 用来处理 recieveHyPCSDKMsg 事件的触发
 * 统一通过 emit 触发消息
 * data: { topic: string, msg: object }
 */
class TopicListener {
  constructor() {
    this.eventer = new EventManager();
    emitManager.on('recieveHyPCSDKMsg', dataStr => {
      const data = baseUtil.toObject(dataStr, {});
      const { topic } = data;

      switch (topic) {
        // 处理Taf类型消息 DEV.Message
        case DEV_MESSAGE:
          this._processTaf(data).catch(err => error.emit(err));
          break;
        // 默认处理方式
        default:
          this._processDEF(data);
      }
    });
  }

  _processDEF(data) {
    const { topic, msg } = data;
    if (!topic) return;

    this.emit(topic, {
      topic,
      msg
    });
  }

  async _processTaf(data) {
    const { DEV } = await prepareHUYA();
    const { topic, msg } = data;
    const devMsg = await tafManager.decode(msg, DEV.Message);
    const { header, body } = devMsg || {};
    if (!header) return;

    const { messType } = header || {};
    const { event, content } = body || {};
    if (!event) return;

    this.emit(`${DEV_MESSAGE}.${messType}`, {
      topic: utils.unescapeHTML(event),
      msg: utils.unescapeHTML(content)
    });
  }

  on(topic, cb, tp) {
    this.eventer.on(topic, cb, tp)
  }

  off(topic, cb, tp) {
    this.eventer.off(topic, cb, tp);
  }

  emit(topic, data) {
    this.eventer.emit(topic, data);
  }
}

export default new TopicListener();