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

const ExtNative = NativeModules.MiniAppLocalMessageCenter;
const ModalUndefined = `MiniAppLocalMessageCenter is undefined`;
const instance = new nativeEventer('extLocalMessage', ExtNative);
instance.setIntercept({
  resReducer: res => {
    if (instance.isAndroid()) return res;
    const { name, params } = res || {};
    const { message } = params || {};
    return { name, params: message };
  },
  beforeOn: (eventName, callback) => {
    if (!instance.isAndroid()) {
      return ExtNative.addLocalMessageListener(eventName);
    }
  },
  afterOff: (eventName) => {
    if (!instance.isAndroid()) {
      return ExtNative.removeLocalMessageListener(eventName);
    }
  }
});

export default {
  async onLocalMessage({ eventName, callback }) {
    if (!ExtNative) throw errUtil.pkgErr(ERR_UNKNOW_API, ModalUndefined);
    return instance.on(eventName, callback);
  },

  async offLocalMessage({ eventName }) {
    if (!ExtNative) throw errUtil.pkgErr(ERR_UNKNOW_API, ModalUndefined);
    return instance.off(eventName);
  },

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