import React, { useEffect,useContext ,useState} from 'react';
import SplashScreen from 'react-native-splash-screen';
import Container from '../components/container';
import { useRoute} from '@react-navigation/native';
import { globalStyles,customStyles,GetPageTheme } from "../styles/Global";
import {StatusBar,Image,TextInput,View,Text,ScrollView,Platform,PermissionsAndroid} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import {get_item,set_item,clear_item} from '../components/localStorage';
import { baseurl, logoImage } from '../constants/constants';


//Splash Screen  
function Splash (props) { 
 
  // get dynamic styles based on dark theme or pageactive 
  const route = useRoute();
  const PageTheme=GetPageTheme(props.DarkMode,route.name);
  const customStyle=customStyles(props.DarkMode,route.name);

  const [state, setState] = useState({islogin:false,firsttime:true});

    useEffect(() => { 
      get_token_from_local();
    }, []);

      
    async function get_token_from_local(){
        // await clear_item('islogin');
        // await clear_item('loginToken');
        let token=await get_item('loginToken');
        let is_login=await get_item('islogin');
        let mpin=await get_item('mpin');
        let firsttime=await get_item('firsttime');
        let ft=(firsttime=='done'?false:true);
        let isl=((is_login=='done' && token!='' && token!=null && token!=undefined)?true:false);
        let is_mpin=(mpin!='' && mpin!=undefined && mpin!=null)?true:false;

        setState({...state,firsttime:ft,islogin:isl})
        const pdata={firsttime:ft,islogin:isl,securityToken:token};
        props.set_session(pdata); 
        navigateToScreen(ft,isl,is_mpin);    
    }

  async function navigateToScreen(firsttime,islogin,ismpinavlbl){
    console.log(firsttime,islogin);
    var routename='';
    if(firsttime){
      routename='Project';
    }
    else if(islogin && ismpinavlbl){
      routename='MpinLogin';//'MpinLogin'; 
    }
    else if(islogin){
      routename='Mpin';//'MpinLogin';      
    }
    else{
      routename='Login';//'MpinLogin';   
    }
    
    //clear stack and navigate 
    props.navigation.reset({index: 0,routes: [{name: routename}],});
    // SplashScreen.hide();
  }

  return ( 
    <Container {...props}>      
      
    </Container>  
  ); 
}

export default connect(mapStateToProps, mapDispatchToProps)(Splash)