import EventManager from '../../../../manager/eventManager';
import logger from '../../../../common/logger';
import messager from '../../common/messager';

const LIFE_EVENT = {
  LOAD: 'load',
  UNLOAD: 'unload',
  ENTER_FOREGROUND: 'enterForeground',
  LEAVE_FOREGROUND: 'leaveForeground',
  APPEAR: 'appear',
  DISAPPEAR: 'disappear'
};

const TPOIC = {
  LOAD: 'life.load',
  UNLOAD: 'life.unload',
  ENTER_FOREGROUND: 'life.enterForeground',
  LEAVE_FOREGROUND: 'life.leaveForeground',
  APPEAR: 'life.appear',
  DISAPPEAR: 'life.disappear'
};

/**
 * 生命周期
 */
class AppState {
  constructor() {
    this.eventer = new EventManager();

    this._loaded = false;
    this.eventer.on(LIFE_EVENT.LOAD, () => {
      this._loaded = true;
    });

    // 监听事件触发
    messager.on(data => {
      switch (data.topic) {
        case TPOIC.LOAD:
          logger.info('触发onLoad生命周期');
          this.eventer.emit(LIFE_EVENT.LOAD);
          break;
        case TPOIC.UNLOAD:
          logger.info('触发onUnload生命周期');
          this.eventer.emit(LIFE_EVENT.UNLOAD);
          break;
        case TPOIC.ENTER_FOREGROUND:
          logger.debug('触发onEnterForeground生命周期');
          this.eventer.emit(LIFE_EVENT.ENTER_FOREGROUND);
          break;
        case TPOIC.LEAVE_FOREGROUND:
          logger.debug('触发onLeaveForeground生命周期');
          this.eventer.emit(LIFE_EVENT.LEAVE_FOREGROUND);
          break;
        case TPOIC.APPEAR:
          logger.debug('触发onAppear生命周期');
          this.eventer.emit(LIFE_EVENT.APPEAR);
          break;
        case TPOIC.DISAPPEAR:
          logger.debug('触发onDisappear生命周期');
          this.eventer.emit(LIFE_EVENT.DISAPPEAR);
          break;
      }
    });
  }

  onLoad(handler) {
    if (this._loaded) {
      setTimeout(() => handler(), 0);
      return true;
    }
    return this.eventer.on(LIFE_EVENT.LOAD, handler);
  }

  onUnload(handler) {
    return this.eventer.on(LIFE_EVENT.UNLOAD, handler);
  }

  onEnterForeground(handler) {
    return this.eventer.on(LIFE_EVENT.ENTER_FOREGROUND, handler);
  }

  onLeaveForeground(handler) {
    return this.eventer.on(LIFE_EVENT.LEAVE_FOREGROUND, handler);
  }

  onAppear(handler) {
    return this.eventer.on(LIFE_EVENT.APPEAR, handler);
  }

  onDisappear(handler) {
    return this.eventer.on(LIFE_EVENT.DISAPPEAR, handler);
  }
}

export default new AppState();