import React ,{useState, useRef, useEffect} from 'react';
// import Tab from '../navigation/TabNavigator';
import C from 'rn-class';
import Main from './_6_Main';
import List from './_7_List';
import TabBar from '../components/TabBar';
import Player from "../components/Player";
//import Player from "./PlayerGesture"; 
import { PlayerConextProvider } from '../components/PlayerReducer'
C.addColor("#d7d7d7", "color-listbg");
import {BTNS_ORG as BTNS} from '../data/dummy';
import { BackHandler  , ToastAndroid} from 'react-native';
// import {ToastAndroid} from 'react-native';

const tabPosition = {x:0, y:0, w:0, h:0};

export default (props)=>{
    const [ sel_idx, setsel_Idx ] =  useState(-1);
    const [ targetIdx, setTargetIdx ] =  useState(-1);
    
    const [ bPlay, setbPlay] =  useState(false); 
    const [ curPlayInfo, setCurPlayInfo] =  useState({});

    const onTabPress = (tIdx, i)=>{
        setsel_Idx(i);
        setTargetIdx(tIdx);
        setbPlay(false);
    }
    const startPlay = (playerData)=>{
        setbPlay(true);
        setCurPlayInfo(playerData);
    }

    let Page;
    if(sel_idx == -1){
        Page = Main;
    }else{
        Page = List; 
    }
    let bClose = false;
    useEffect(()=>{
        BackHandler.addEventListener(
            'hardwareBackPress',
            ()=>{
                if(props.navigation.isFocused()){
                    if(bClose){
                        // console.log(BackAndroid); 
                        BackHandler.exitApp();
                    }
                    bClose =true ;
                    ToastAndroid.show('한번더 뒤로 가기를 누르면 종료 됩니다.', ToastAndroid.SHORT);
                    setTimeout(()=>{
                        bClose = false;
                    },800)
                }
                
                // 소형화 로직
                
                return  props.navigation.isFocused();
            }    
        )
        return () => {
            console.log('will unmount');
          }
    },[]);

    const setTabPosition = (data) => { 
        tabPosition.x = data.x;
        tabPosition.y = data.y;
        tabPosition.w = data.w;
        tabPosition.h = data.h;
    }

    return (
        <C.View cls="flx1 bgc-color-white"> 
            <C.Comp.Header  {...props}/>
            <Page   {...props} Pages={sel_idx == -1 ? {} : BTNS[targetIdx][sel_idx]}  startPlay={startPlay} bPlay={bPlay}/>
            <PlayerConextProvider>
                {bPlay ? <Player playerData={curPlayInfo} tabPosition={tabPosition} closePlayer={()=>setbPlay(false)}/>  : null}
            </PlayerConextProvider>
            <TabBar setTabPosition={setTabPosition} onTabPress={onTabPress} BTNS={BTNS}/>  
        </C.View> 
    )  

}

