/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, { Fragment } from 'react';
import { StatusBar, SafeAreaView, Modal, View, Text, ActivityIndicator, AppState, Image } from 'react-native';
import Navigator from '~/Screens/Navigator';
import { Provider } from 'react-redux';
import configureStore from '~/configureStore';
import * as Font from 'expo-font';
import { SelectboxListProvider } from './Components/UIControls/Selectbox';
import { DateTimePickerProvider } from './Components/UIControls/DateTimePicker';
import { Util } from './Utils/utils';
import { SearchProvider } from './Components/Listing/Search';
import { PopupProvider } from './Components/UIControls/Popup/Provider';
import { PromptProvider, showMessage, confirm, MessageProvider, alert } from './Components/UIControls/Message';
import session from './Utils/session';
import { Updates, SplashScreen } from 'expo';
import { SplashProvider } from './Components/Splash';
import { MonthPickerProvider } from './Components/UIControls/MonthPicker';
import { UploadFileProvider } from './Components/UIControls/UploadFile';
import { CameraProvider } from './Components/UIControls/CameraProvider';
import { PhoneProvider } from './Components/UIControls/Phone';
import { DownloadProvider } from './Components/UIControls/Download';
import * as Notifications from 'expo-notifications';

const preloadedState = {};
export const store = configureStore(preloadedState);

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

class App extends React.Component {
  state = {
    fontLoaded: false,
    updating: false,
    appState: AppState.currentState,
    expoPushToken: '',
  };

  checkForUpdates = async () => {
    try {
      const update = await Updates.checkForUpdateAsync();
      if(update.isAvailable) {
        confirm('업데이트 알림', '새로운 버젼이 있습니다. 업데이트 하시겠습니까?', () => {
          this.runUpdate();
        });
      }
    } catch (error) {
      showMessage(error.message);
    }
  }

  runUpdate = async () => {
    this.setState({ ...this.state, updating: true });

    await Updates.fetchUpdateAsync();
    Updates.reloadFromCache();

    this.setState({ ...this.state, updating: false });
  }

  handleAppStateChange = (nextAppState) => {
    if(this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      // onresume
      if(!__DEV__) {
        this.checkForUpdates();
      }
    }
    this.setState({...this.state, appState:nextAppState});
  }

  handleNotification = (notification) => {
    console.log(notification);
  }

  handleNotificationResponse = (response) => {
    console.log(response);
  }

  componentDidMount = async () => {
    SplashScreen.preventAutoHide();

    if(!__DEV__) {
      this.checkForUpdates();
    }

    AppState.addEventListener('change', this.handleAppStateChange);

    /*
    Notifications.addNotificationReceivedListener(this.handleNotification);
    Notifications.addNotificationResponseReceivedListener(this.handleNotificationResponse);
    */

    await Font.loadAsync({
      'NotoSansCJKkr-Black': require('~/Assets/Fonts/NotoSansKR-Black.otf'),
      'NotoSansCJKkr-Bold': require('~/Assets/Fonts/NotoSansKR-Bold.otf'),
      'NotoSansCJKkr-DemiLight': require('~/Assets/Fonts/NotoSansKR-DemiLight.otf'),
      'NotoSansCJKkr-Light': require('~/Assets/Fonts/NotoSansKR-Light.otf'),
      'NotoSansCJKkr-Medium': require('~/Assets/Fonts/NotoSansKR-Medium.otf'),
      'NotoSansCJKkr-Regular': require('~/Assets/Fonts/NotoSansKR-Regular.otf'),
      'NotoSansCJKkr-Thin': require('~/Assets/Fonts/NotoSansKR-Thin.otf'),

      'Roboto-Black': require('~/Assets/Fonts/Roboto-Black.ttf'),
      'Roboto-Bold': require('~/Assets/Fonts/Roboto-Bold.ttf'),
      'Roboto-Light': require('~/Assets/Fonts/Roboto-Light.ttf'),
      'Roboto-Medium': require('~/Assets/Fonts/Roboto-Medium.ttf'),
      'Roboto-Regular': require('~/Assets/Fonts/Roboto-Regular.ttf'),
      'Roboto-Thin': require('~/Assets/Fonts/Roboto-Thin.ttf'),

      'Roboto-Black-Italic': require('~/Assets/Fonts/Roboto-BlackItalic.ttf'),
      'Roboto-Bold-Italic': require('~/Assets/Fonts/Roboto-BoldItalic.ttf'),
      'Roboto-Light-Italic': require('~/Assets/Fonts/Roboto-LightItalic.ttf'),
      'Roboto-Medium-Italic': require('~/Assets/Fonts/Roboto-MediumItalic.ttf'),
      'Roboto-Regular-Italic': require('~/Assets/Fonts/Roboto-Italic.ttf'),
      'Roboto-Thin-Italic': require('~/Assets/Fonts/Roboto-ThinItalic.ttf'),
    });
    await session.load();

    this.setState({ ...this.state, fontLoaded: true });
  }

  componentWillUnmount = () => {
    AppState.removeEventListener('change', this.handleAppStateChange);
  }

  render = () => {

    console.log('appState : ', this.state.appState);

    return (
      <Fragment>
        <SplashProvider>
          {this.state.fontLoaded ? (
            <Provider store={store}>
              <StatusBar translucent={true} barStyle={Platform.OS == 'android' ? 'default' : 'dark-content'} />
              <SafeAreaView style={{ flex: 1, marginTop: Util.getStatusBarHeight(), backgroundColor:'#ffffff' }}>
                <SearchProvider>
                  <PopupProvider>
                      <Navigator />
                  </PopupProvider>
                </SearchProvider>
              </SafeAreaView>
              
              <SelectboxListProvider />
              <DateTimePickerProvider />
              <MonthPickerProvider />
              <PromptProvider />
              <MessageProvider />
              <UploadFileProvider />
              <CameraProvider />
              <PhoneProvider />
              <DownloadProvider />
            </Provider>
          ) : null}
        </SplashProvider>
        {this.state.appState.match(/inactive|background/) ? (
          <View 
            style={{
              position:'absolute', left:0, right:0, top:0, bottom:0, backgroundColor:'black'
            }}
          >
                <Image
                    style={{width:'100%', height:'100%'}}
                    source={require('./../assets/splash.png')}
                    resizeMode="cover"
                    onLoadEnd={() => {}}
                    fadeDuration={0}
                />
          </View>
        ) : null}
        <Modal visible={this.state.updating} transparent={true} animationType="fade">
          <View style={{ 
              position:'absolute', flexDirection:"column", 
              left:'10%', top:'35%', right:'10%', bottom:'35%', 
              alignItems:'center', justifyContent:'space-between', 
              borderRadius:10, backgroundColor:'#0b83e6', overflow:'hidden' 
            }}>
              <View style={{width:'100%', height:50, backgroundColor:'#0543a6', alignItems:'center', justifyContent:'center'}}>
                <Text style={{ fontSize:20, letterSpacing:-1.2, color:'white' }}>업데이트</Text>
              </View>
              <View style={{ flex:1, alignItems:'center', justifyContent:'center' }}>
                <ActivityIndicator size="large" color="white" style={{marginBottom:30}} />
                <View style={{ flexDirection:'column', alignItems:'center', justifyContent:'center' }}>
                  <Text style={{ fontSize:20, letterSpacing:-1.2, color:'white'}}>업데이트 중입니다.</Text>
                  <Text style={{ fontSize:20, letterSpacing:-1.2, color:'white'}}>잠시만 기다려주세요.</Text>
                </View>
              </View>
          </View>
        </Modal>
      </Fragment>
    );
  }
}

export default App;
