import {NativeModules, DeviceEventEmitter} from 'react-native';
import mitt from '../utils/mitt';

// 事件常数值参考：https://www.apiref.com/android-zh/android/view/accessibility/AccessibilityEvent.html

let AutoClick = {};
const emitter = mitt();

if (!NativeModules.AutoClick) {
  AutoClick = {
    isSettingsOn: async () => true,
  };
} else {
  AutoClick = {
    isSettingsOn: async () => {
      const enable = await NativeModules.AutoClick.isSettingsOn();
      AutoClick.enable = enable;
      return enable;
    },
    goSetting: NativeModules.AutoClick.goSetting,
    clickBackKey: () => {
      const {clickBackKey} = NativeModules.AutoClick;
      return clickBackKey && clickBackKey();
    },
    setEvent: (...arg) => {
      const {setEvent} = NativeModules.AutoClick;
      setEvent && setEvent(...arg);
    },
    ...emitter,
  };

  const wxPkg = 'com.tencent.wxpayface';
  const alPkg = 'com.alipay.zoloz.smile';
  const events = {
    wxpayfaceConfirm: {
      pkgName: wxPkg,
      method: 'clickByText',
      search: '确认支付',
      parent: true,
    },
    wxpayfaceRegister: {
      pkgName: wxPkg,
      method: 'clickById',
      search: `${wxPkg}:id/container_register_allow_button`,
      parent: false,
    },
    wxpayscoreRegister: {
      pkgName: wxPkg,
      method: 'clickByText',
      search: '申请授权',
      parent: true,
    },
    smileConfirm: {
      pkgName: alPkg,
      method: 'clickByExact',
      search: '确认',
      parent: true,
    },
    smilePayConfirm: {
      pkgName: alPkg,
      method: 'clickByExact',
      search: '确认支付',
      parent: true,
    },
  };

  Object.keys(events).map(key => {
    AutoClick.setEvent(key, events[key]);
  });
  DeviceEventEmitter.addListener('AccessibilityEvent', e => {
    if (e && e.key) emitter.emit(e.key);
  });
  DeviceEventEmitter.addListener('AccessibilityClick', e => {
    emitter.emit('AccessibilityClick', e);
  });
  // 兼容旧版本代码
  DeviceEventEmitter.addListener('wxpayfaceInput', e => {
    emitter.emit('AccessibilityClick', e);
  });
  DeviceEventEmitter.addListener('wxpayfaceRegister', () => {
    emitter.emit('wxpayfaceRegister');
  });
}

export default AutoClick;
