import baseUtil from '../../../utils/base';
import strRender from '../../../utils/strRender';
import { silenceLogger } from '../../../common/logger';
import messager from '../common/messager';
import topicListener from '../common/topicListener';


let nowTargetId = Date.now() + 10000; // 事件监听唯一标识
export default {
  /**
   * 调用方法并绑定事件
   * @param {*} topic 
   * @param {*} cb 
   * @param {*} opts 
   */
  onEvent(moduleName, topic, opts, cb) {
    if (baseUtil.isFun(opts)) {
      cb = opts;
      opts = null;
    }

    const { callback: optCallback } = opts || {};
    const callback = cb || optCallback || function () { };
    const target = `${topic}Target_${nowTargetId++}`;
    const params = { target };
    if (opts) {
      params.options = { ...opts, callback: 'CALLBACK' };
    }

    const type = strRender.getEventNameFromTopic(topic);
    const eventType = strRender.genEventType(moduleName, type, opts);

    silenceLogger.debug('onEvent', topic, target, eventType);
    topicListener.on(target, callback, eventType);
    return messager.dispatch(topic, params)
    // .then(res => {
    //   const data = (baseUtil.isObject(res) && res) || {};
    //   data._hyEventId = target;
    //   return data
    // });
  },

  /**
   * 注销事件监听
   * @param {*} topic 
   * @param {*} opts 
   */
  offEvent(moduleName, topic, opts, cb) {
    if (baseUtil.isFun(opts)) {
      cb = opts;
      opts = null;
    }

    const { _hyEventId, callback: optCallback, ...params } = opts || {};
    const type = strRender.getEventNameFromTopic(topic);
    const eventType = strRender.genEventType(moduleName, type, params);

    silenceLogger.debug('offEvent', topic, eventType);
    topicListener.off(_hyEventId, cb || optCallback, eventType);
    return messager.dispatch(topic, params);
  },

  /**
   * 普通事件调用，没返回值或返回的不是 Promise
   * @param {*} moduleName 模块名
   * @param {*} topic 方法名
   * @param {...any} params 传参
   */
  callEventSync(moduleName, topic, ...params) {
    silenceLogger.debug('callEventSync', moduleName, topic);

    return messager.emit(topic, ...params);
  },

  /**
   * 异步事件调用，返回 Promise
   * @param {*} moduleName 模块名
   * @param {*} topic 方法名
   * @param {...any} params 传参
   */
  callEvent(moduleName, topic, ...params) {
    silenceLogger.debug('callEvent', moduleName, topic);

    return messager.dispatch(topic, ...params);
  }
}