import React,{useState,useEffect} from 'react';
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,TouchableOpacity,Platform,PermissionsAndroid,FlatList} from 'react-native';
import { ReactReduxContext,connect,useSelector, useDispatch  } from 'react-redux';
import { mapStateToProps,mapDispatchToProps } from '../reducers/contextProvider';
import SQLite from 'react-native-sqlite-2';
import {notify} from '../components/notify';
import moment from 'moment';
import {getDownloadJson,DownloadData} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card} from 'react-native-paper';
import {AntDesign} from '../components/icons';
import CustomLoader from '../components/CustomLoader';

function DownloadDataScreen(props) { 
    const route = useRoute();
  
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
  
    const [state, setState] = useState({isDataDownloaded: false});
    const [teamList, setTeamList] = useState([]);
    const [masterBrand, setMasterBrand] = useState([]);
    const [skuSize, setSkuSize] = useState([]);
    const [compType, setCompType] = useState([]);
    const [skuPacking, setSkuPacking] = useState([]);  
    const [flavours, setFlavours] = useState([]);  
    const [AuditQtns, setAuditQtns] = useState([]);  
    const [imageTypes, setImageTypes] = useState([]);  
    const [processing, setProcessing] = useState(false);
    const [dowloadedCount, setDowloadedCount] = useState(-1);
    const totalCount=8;

    

  useEffect(() => {
    console.log('processing:',processing);
    if(processing){
    console.log('increment dowloadedCount changed');
    let count=dowloadedCount+1;
    setDowloadedCount(count);
    }
  }, [teamList,skuSize,compType,skuPacking,flavours,AuditQtns,imageTypes]);

  

  useEffect(() => {
    console.log('dowloadedCount changed',dowloadedCount);
    if(dowloadedCount<=totalCount){
      dowloadAllData();
    }
    else{
      setProcessing(false); 
    }
  }, [dowloadedCount]);

 

  async function startDownload() {
    setProcessing(true); 
    setDowloadedCount(0);
  }


  async function dowloadAllData() { 
    console.log('dowloadAllData',dowloadedCount);
    let token = await get_item('loginToken');
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);
    let teamArr=[],Master_Brand=[],Brand_Category=[],Master_SkuSize=[],Master_SkuPacking=[],Master_CompType=[],Qtns=[],imgTypes=[],Master_ProductFlavour=[];

    if(dowloadedCount==0){
    // download teamlist
    var data = {Downloadtype: 'Sup_TeamList',username: loginDetails.UserId,empid: '',token: token,};
    await getDownloadJson(testurl, data)
      .then(async(res) => {        
        if (res.Sup_TeamList) {
          teamArr = res.Sup_TeamList || [];
          setTeamList(teamArr);
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
      });

      return;
    }
   
    if(dowloadedCount==1){
    // download Brand_master
    data = {Downloadtype: 'Master_Brand',username: loginDetails.UserId,empid: '',token: token,};
    await getDownloadJson(testurl, data)
      .then(async(res) => {        
        if (res.Master_Brand) {
          Master_Brand = res.Master_Brand || [];
          setMasterBrand(Master_Brand); 
        }
        else if(res.success==false && res.error){
          notify('Something went wrong while downloading data!');
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
    });

    return;

    }
    

    if(dowloadedCount==2){

    // download SKU Sizes
    data = {Downloadtype: 'Master_SkuSize',username: loginDetails.UserId,empid: '',token: token,};
    await getDownloadJson(testurl, data)
      .then(async(res) => {        
        if (res.Master_SkuSize) {
          Master_SkuSize = res.Master_SkuSize || [];
          setSkuSize(Master_SkuSize); 
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
    });

    return;

    }


    if(dowloadedCount==3){
    // download SKU Packaging
    data = {Downloadtype: 'Master_ProductPack',username: loginDetails.UserId,empid: '',token: token,};
    await getDownloadJson(testurl, data)
      .then(async(res) => {        
        if (res.Master_ProductPack) {
          Master_SkuPacking = res.Master_ProductPack || [];
          setSkuPacking(Master_SkuPacking); 
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
    });

    return;

    }


    if(dowloadedCount==4){
    // download comp type
    data = {Downloadtype: 'Master_ActivationType',username: loginDetails.UserId,empid: '',token: token,};
    await getDownloadJson(testurl, data)
      .then(async(res) => {        
        if (res.Master_ActivationType) {
          Master_CompType = res.Master_ActivationType || [];
          setCompType(Master_CompType); 
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
    });

    return;

    }

    if(dowloadedCount==5){
    // download product Flavour    
    data = {Downloadtype: 'Master_ProductFlavour',username: loginDetails.UserId,empid: '',token: token,};
    await getDownloadJson(testurl, data)
      .then(async(res) => {        
        if (res.Master_ProductFlavour) {
          Master_ProductFlavour = res.Master_ProductFlavour || [];
          setFlavours(Master_ProductFlavour); 
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
    });

    return;

    }

    if(dowloadedCount==6){
    // download product Flavour    
    data = {Downloadtype: 'Sup_AuditQuestion',username: loginDetails.UserId,empid: '',token: token,};
    await getDownloadJson(testurl, data)
      .then(async(res) => {        
        if (res.Sup_AuditQuestion) {
          Qtns = res.Sup_AuditQuestion || [];
          setAuditQtns(Qtns);
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
    });
      return;
    }

    if(dowloadedCount==7){
    // download Sup_ImageType
    data = {Downloadtype: 'Sup_ImageType',username: loginDetails.UserId,empid: '',token: token,};
    await getDownloadJson(testurl, data)
      .then(async(res) => {        
        if (res.Sup_ImageType) {
          imgTypes = res.Sup_ImageType || [];
          setImageTypes(imgTypes);
        }
      })
      .catch(err => {
        console.log('onPage Team error', err);
    });

    return;

    }
    

    if(dowloadedCount==8){
    // create tables for if not created
    let ddata={isDataDownloaded:false,teamList:teamList,Master_ActivationType:compType,Master_Brand:masterBrand,Master_ProductPack:skuPacking,Master_SkuSize:skuSize,Master_ProductFlavour:flavours,Sup_AuditQuestion:AuditQtns,Sup_ImageType:imageTypes};
    await DownloadData(props,ddata).then(()=>{
      setState({...state,isDataDownloaded:true});
      setProcessing(false);
      notify('Data Downloaded','SHORT');
      props.navigation.goBack();   
    });
    }

  }

  
    return ( 
      <Container {...props} pt={0}>
        {processing && <CustomLoader title={`Downloading files : ${dowloadedCount}/${totalCount}`}/>}
        <CustomHeader {...props} showaddstore={true} topM={18} title={'Download Data'}/>
        <ScrollView
            style={[customStyle.download_scroll]}
            contentContainerStyle={customStyle.download_scroll_con}
        >
            <TouchableOpacity style={customStyle.downloadbtn} onPress={()=>{startDownload()}}>
              <Text style={customStyle.downloadbtn_label}>Download Data</Text>
            </TouchableOpacity>  
        </ScrollView>   
      </Container>   
    ); 
  }
  
  

export default connect(mapStateToProps, mapDispatchToProps)(DownloadDataScreen);