import nativeEventer from '../../common/nativeEventer';
import modeManager from '../../common/modeManager';


const ExtNative = modeManager.getModule('MiniAppContext');
const ExtEventName = modeManager.getName('miniAppContextEvent');
const instance = new nativeEventer(ExtEventName, ExtNative);
instance.setIntercept({
  resReducer: data => {
    if (!instance.isAndroid()) return data;
    const { params } = data || {};
    const { res } = params || {};
    const { roomId, startTime, endTime } = res || {};
    if (roomId) {
      res.roomId = parseInt(roomId);
    }
    if (startTime) {
      res.startTime = parseInt(startTime);
    }
    if (endTime) {
      res.endTime = parseInt(endTime);
    }
    return data;
  },
  beforeOn: (eventName, callback, options) => {
    if (instance.isAndroid()) {
      return ExtNative.postEventFilterOption(eventName, options);
    }
    return ExtNative.addEventListener(eventName, options);
  },
  afterOff: (eventName, callback, options) => {
    if (!instance.isClean()) {
      return;
    }

    if (instance.isAndroid()) {
      return ExtNative.postEventFilterOption(eventName, null);
    }

    return ExtNative.removeEventListener(eventName);
  },
});

export default {
  on(event, callback) {
    return instance.on(event, callback).catch(err => { });
  },

  off(event, callback) {
    return instance.off(event, callback).catch(err => { });
  },

  onBarrageChange(options, callback) {
    return instance.reset('barrageChange', callback, options);
  },

  offBarrageChange() {
    return instance.off('barrageChange');
  },

  onLayoutChange(callback) {
    return instance.on("onLayoutChange", callback);
  },

  onAppear(callback) {
    return instance.on("onAppear", callback);
  },

  onDisappear(callback) {
    return instance.on("onDisappear", callback);
  },
}