// eslint-disable-next-line import/no-unresolved
import { AppState } from 'react-native';
import MiniAppContext from '../MiniAppContext';
import baseUtil from '../../../../utils/base';

/**
 * TODO: 将生命周期放到adapter 里，通过全局事件联动
 * 生命周期
 */
class ExtAppState {
  constructor() {
    this._appState = AppState.currentState;
    this.enterForegroundCallback = [];
    this.leaveForegroundCallback = [];

    AppState.addEventListener('change', (nextAppState) => {
      if (this._appState.match(/inactive|background/) && nextAppState === 'active') {
        this.enterForegroundCallback.map(callback => callback());
      }
      else if (this._appState === 'active' && nextAppState.match(/inactive|background/)) {
        this.leaveForegroundCallback.map(callback => callback());
      }
      this._appState = nextAppState;
    });
  }

  onLoad(callback) {
    if (baseUtil.isFun(callback)) {
      callback();
    }
  }

  onEnterForeground(callback) {
    if (baseUtil.isFun(callback)) {
      this.enterForegroundCallback.push(callback);
    }
  }

  onLeaveForeground(callback) {
    if (baseUtil.isFun(callback)) {
      this.leaveForegroundCallback.push(callback);
    }
  }

  onAppear(callback) {
    return MiniAppContext.onAppear(callback);
  }

  onDisappear(callback) {
    return MiniAppContext.onDisappear(callback);
  }
}

export default new ExtAppState();