// eslint-disable-next-line import/no-unresolved
import { NativeModules } from 'react-native';
import nativeEventer from '../../common/nativeEventer';

const ExtNative = NativeModules.HYLMiniAppObserver;
const instance = new nativeEventer('hylMiniAppObserverEvent', ExtNative);
instance.setIntercept({
  resReducer: res => {
    if (instance.isAndroid()) return res;
    const { event, content } = res || {};
    return { name: event, params: content };
  },
});

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

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

  async onLocalMessage({ eventName, callback }) {
    instance.on(eventName, callback);
    return await ExtNative.onLocalMessage(eventName);
  },

  async offLocalMessage({ eventName }) {
    instance.off(eventName);
    return await ExtNative.offLocalMessage(eventName);
  },

  async postLocalMessage({ eventName, message }) {
    return await ExtNative.postLocalMessage(eventName, message);
  }
}
