/**
 * @flow
 */

import React, { Component } from 'react';
import { AppState, Text, SafeAreaView, BackHandler, ToastAndroid } from 'react-native';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/es/integration/react';
import configureStore from './basicStore';
import BasicNavigator from './BasicNavigator';
import StyleSheet from './utils/StyleSheet';
import { pop } from './BasicNavigator/actions';

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
})

const { store, persistor } = configureStore()

class MainApp extends Component {
  componentDidMount() {
    //if (AssetsModule.dismisToast) {
    //  AssetsModule.dismisToast()
    //}
    BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
    AppState.addEventListener('change', this.handleAppChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this.handleAppChange);
    BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
    //if (AssetsModule.dismisToast) {
    //  AssetsModule.dismisToast()
    //}
  }

  handleAppChange = (currentAppState : string) => {
    //console.log('handleAppChange:')
    if (currentAppState === 'active') {
      //checkForUpdate(true)
      console.log('handleAppChange','active');
    }
  }

  onBackPress = () => {
    console.log('onBackPress');
    //这里的路由信息是你自己项目中的，通过这个原理，我们还是可以提示一些其他信息，比如表单没填写完整等等
    const state = store.getState()
    if (state.nav.routes.length <= 1) {
      if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
        //最近2秒内按过back键，可以退出应用。
        BackHandler.exitApp();
        return false;
      }
      this.lastBackPressed = Date.now();
      ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
      return true;
    }
    store.dispatch(pop());
    return true;
  }


  render() {
    return (
      <Provider store={store}>
        <PersistGate loading={<Text>MyLoading...</Text>} persistor={persistor}>
          <SafeAreaView style={styles.container}>
            <BasicNavigator param={this.props} />
          </SafeAreaView>
        </PersistGate>
      </Provider>
    );
  }
}

export default MainApp;
