import React,{useState,useEffect, useRef} 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, DeviceEventEmitter} 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, getIRPendingSessionCount, UploadData2} from '../controller/functions';
import {get_item,set_item,clear_item} from '../components/localStorage';
import {version,sloganline,appname,testurl, db} from '../constants/constants';
import CustomHeader from '../components/customHeader';
import {Card} from 'react-native-paper';
import {AntDesign, Ionicons} from '../components/icons';
import { WebView } from 'react-native-webview';
import CustomLoader from '../components/CustomLoader';
import NoDataComponent from '../components/NoDataComponent';
import LinearGradient from 'react-native-linear-gradient';
import { getPendingIRImagesDetails,getPendingIRImages, SyncIRsessions } from '../constants/uploadData';
import IRLogin from '../components/IRLogin';
import { AppName, PerformicsIRAppName } from '../../../AppSpecificContant';
import DownloadDataModal from '../components/downloadDataModal';
import { METHODS, getMethodName } from '../constants/methodNames';
import { AppTables } from '../constants/tableConstants';

function IRPendingDetails(props) { 
    const route = useRoute();
    const ST=props.StaticText || {};
    // get all theme styles acc to current theme set 
    const PageTheme=GetPageTheme(props.DarkMode,route.name);
    const customStyle=customStyles(props.DarkMode,route.name);
  
    const [webviewurl, setWebviewurl] = useState(false);
    const [processing, setProcessing] = useState(true);
    const [isDataFound, setisDataFound] = useState(false);
    const [reportData, setReportData] = useState([]);
    const [designation, setDesignation] = useState('');
    const [rerender, setrerender] = useState(0);

    // IR Upload states
    const [uploadedCount, setUploadedCount] = useState(0);
    const [TotalUpCount, setTotalUpCount] = useState(0);
    const [startUploading, setStartUploading] = useState(false);
    const [UploadingSubText, setUploadingSubText] = useState("");
    const [UploadingText, setUploadingText] = useState("Uploading Data...");
    const [showProgresssBar, setshowProgresssBar] = useState(false);
    const [subTextStyle, setSubTextStyle] = useState('');
    const [showOkButtonOnUpload, setShowOkButtonOnUpload] = useState(false);

    const sessionsToUpload=useRef([]);
    const sessionsUploadedCount=useRef(0);
    const sessionsReceived=useRef(0);

    const d1=new Date();
    const d2=moment(d1).format('MM/DD/YYYY');
  
    useEffect(() => {
      getData();

      const removeIRListener=DeviceEventEmitter.addListener('onPendingSingle_IRImageUpload',(data)=>{ onIRImageUpload(data)});
    
      return function cleanup() {
        if(props.IR_CameraEnableOnApp==true){
          IRLogin.deRegisterReceiver();
        }
        removeIRListener.remove();  
      };
    }, []);
    
 
    async function getData(){        
      try {   
      
        let allPendingImagesList=await getPendingIRImages(props);
        setReportData(allPendingImagesList);
        setProcessing(false);
        setisDataFound(true);
        console.log("allPendingImagesList",allPendingImagesList);

        // db.transaction(async function (txn) {
        //   await txn.executeSql(`update ${AppTables.SOS_IRUPLOAD} set SYNC_STATUS='Failed' `,[],async function (txn2, txnres) { 
        //     console.log("updated SYNC_STATUS");
        //   },function (txnE,txnerr) { console.log(txnerr);resolve(sessionListWithDetails);},);
        //   await txn.executeSql(`update ${AppTables.WINDOW_IRUPLOAD} set SYNC_STATUS='Failed' `,[],async function (txn2, txnres) { 
        //     console.log("updated SYNC_STATUS PV");
        //   },function (txnE,txnerr) { console.log(txnerr);resolve(sessionListWithDetails);},);
        // });
              
      } catch (err) {
        setProcessing(false);
        console.log(err);          
      }        
    }

    function gotoReport(item){
      props.navigation.navigate('ReportDetail',{'ReportData':item})
    }


    async function UpdateUploadCountLocal(upCount){
      // keep 1 less to actual count as DownloadDataModal shows it as provided_value+1
      setUploadedCount(upCount-1);
    } 

    // Start uploading IR sessions for particular store 
    async function uploadIRSession(item){
      let {StoreId,VisitDate,SessionCount,ImageCount,TableName1,TableName2,ScreenName,StoreCode,StoreName,MenuName }=item
      setStartUploading(true);

      // function to stop uploading and hide upload modal 
      function stopUploading(){
        setStartUploading(false);
      }
  
  
      // start IR Upload
      UpdateUploadCountLocal(0); // set uploaded count in progress bar to zero as IR session upload is just started
      setTotalUpCount(0);// set Total uploaded count to 0
      setshowProgresssBar(false);
      setUploadingSubText('');
      setUploadingText('Syncing IR Sessions Status...');
      sessionsToUpload.current=[];
      sessionsReceived.current=0;
      sessionsUploadedCount.current=0;
      let sync_result=await SyncIRsessions(props,"3",true,item);
      let {isUploadStarted,noDataFound,AllDataUploaded,success,sessionList,sessionListWithDetails}=sync_result;
      
      if(!success){
        notify('Cannot Upload Data! Something went wrong.');
        stopUploading();
      }
      else{
          if(noDataFound){
              notify('No session to upload!');
              stopUploading();
          }
          else{
              if(!isUploadStarted && AllDataUploaded){
                  notify('All images synced! No session to upload.');
                  stopUploading();
              }else if(isUploadStarted){
                  
                  sessionsToUpload.current=sessionListWithDetails;
                  console.log("UploadStarted",sessionsToUpload.current.length);
                  UpdateUploadCountLocal(0); // set uploaded count in progress bar to zero as IR session upload is just started
                  setTotalUpCount(sessionsToUpload.current.length-1); // set Total Upload Count to IR Session Counts
                  setshowProgresssBar(true);
                  setUploadingSubText('Uploading IR Sessions');
                  setUploadingText('Uploading IR Sessions Data...');
                  //set a timeout for session uploading: if no response get from receiver for particular session
                  for(let i=0;i<sessionListWithDetails.length;i++){
                    let {TEMP_SESSION_ID}=sessionListWithDetails[i];
                    
                    setTimeout(async ()=>{
                      
                      let timerSessI=sessionsToUpload.current.findIndex(i=>i.TEMP_SESSION_ID==TEMP_SESSION_ID);
                      let timerSessObj=timerSessI>=0?sessionsToUpload.current[timerSessI]:{};
                     
                      if(timerSessObj.IRStatusReceived!=null && timerSessObj.IRStatusReceived===true){
                        console.log("Session is already uploaded")
                      }
                      else{ // upload local timout message and move loading to next step after 60 sec if no response received from server
                        let udata={"message": "Session Upload Timeout", "sessionId": TEMP_SESSION_ID, "status": "local"}
                        // let udata={"message": "Session Uploaded Test", "sessionId": TEMP_SESSION_ID, "status": "200"}
                        await onIRImageUpload(udata);
                      }
                    },60*1000);
                  }
              }
          }
      }
    }
  
    async function onIRImageUpload(data){
      console.log('onPendingSingle_IRImageUpload on receive in STorelist',data);
      let {message,sessionId,status}=data;
      let snum=sessionsReceived.current+1;
      let su_num=sessionsUploadedCount.current;
      sessionsReceived.current=snum;
  
      
      
      let sessionIndex=sessionsToUpload.current.findIndex(i=>i.TEMP_SESSION_ID==sessionId);
      let sessionObj=sessionIndex>=0?sessionsToUpload.current[sessionIndex]:{};
      console.log('onPendingSingle_IRImageUpload on receive in sessionObj',sessionId,sessionObj);
      let TableName1=sessionObj['TableName1'] || '';
      let TableName2=sessionObj['TableName2'] || '';
      let StoreId=sessionObj['StoreId'] || '';
      let StoreName=sessionObj['StoreName'] || '';
      
      let IRCategoryName=sessionObj["IRCategoryName"] || '';
      let IRTaskName=sessionObj["IRTaskName"] || '';
      let IRPhotoType=sessionObj["IRPhotoType"] || '';
      let IRStoreCode=sessionObj["IRStoreCode"] || '';
      let ScreenName=sessionObj["ScreenName"] || '';
      let VisitDate=sessionObj["VisitDate"] || '';
      let IRDetails={IRCategoryName,IRTaskName,IRPhotoType,IRStoreCode,ScreenName}
      
      // if any status for the given session is recieved then we don't need to run timer and send local timout for that session 
      // so update its IRStatusReceived to true 
      sessionObj.IRStatusReceived=true;
      sessionsToUpload.current[sessionIndex]=sessionObj;
      
      // check if session is uploaded then upload its logs
      if(status!=null && status=='200' && sessionId!=null && sessionId!=''){
          sessionsUploadedCount.current=++su_num;
          console.log("total uploaded count su_num:",su_num);
          // update session uploaded count
          UpdateUploadCountLocal(su_num);

          let UnSessionId=await IRLogin.getDataIRSession(sessionId);
          if(UnSessionId!=null && UnSessionId!=''){
              
              
              let isUpdated=await UpdateIRUploadStatus(sessionId,UnSessionId,TableName1,TableName2,StoreId,IRDetails);
              let isUploaded=await LogImageUpload(sessionId,UnSessionId,message,status,StoreId,StoreName,TableName1,TableName2,IRDetails);
              if(isUploaded){
                  console.log('Image Uploaded');
                  notify("Images Log uploaded for session:"+sessionId);
              }
              else{
                  console.log('cannot Uploaded image');
                  notify("cannot upload log for session:"+sessionId);
              }
          }
          else{
              notify("Cannot upload images for session:"+sessionId+". Universal Id not found");
              let isUploaded=await LogImageUpload(sessionId,"",message,status,StoreId,StoreName,TableName1,TableName2,IRDetails);
              if(isUploaded){
                  console.log('Image Uploaded');
                  notify("Images Log uploaded for session:"+sessionId);
              }
              else{
                  console.log('cannot Uploaded image');
                  notify("cannot upload log for session:"+sessionId);
              }
          }
          
      }
      else{
          notify((message!=null && message!=""?message+". ":"")+"Cannot upload images for session:"+sessionId);
          let isUploaded=await LogImageUpload(sessionId,"",message,status,StoreId,StoreName,TableName1,TableName2,IRDetails);
          if(isUploaded){
              console.log('Image Uploaded');
              notify("Images Log uploaded for session:"+sessionId);
          }
          else{
              console.log('cannot Uploaded image');
              notify("cannot upload log for session:"+sessionId);
          }
          
      }
      
      console.log("check snum and su_num:",snum,su_num,sessionsToUpload.current.length);
      
      let popupMsg="";
      let subTstyle={};
      let isUploaded=false;
      // All IR Sessions with Images Uploaded : set DataUploaded Status to U (Fully Upload)
      if(su_num==sessionsToUpload.current.length){
        // setProcessing(false);
        // setStartUploading(false);
        popupMsg="All IR images uploaded!";
        subTstyle={color:'green'};
       
        notify("All IR images uploaded!");
        console.log('set all uploaded true to U');
        isUploaded=true;
      }
      // Some Of IR Sessions with Images Uploaded but some are yet pending : set DataUploaded Status to P (Partial Upload)
      else if(su_num>0 && su_num!=sessionsToUpload.current.length){
          // setProcessing(false);
          popupMsg=`${su_num} out of ${sessionsToUpload.current.length} IR Sessions uploaded! Please Retry`;
          subTstyle={color:'red'};
          notify("Uploading IR Sessions!");
          console.log('set all uploaded true to P');
      }
      else if(su_num==0){
        subTstyle={color:'red'};
        popupMsg=`${su_num} out of ${sessionsToUpload.current.length} IR Sessions uploaded! Please Retry`;
      }
  
      console.log("IR Session received ",snum)
      

      
      // if last broadcast received either uploaded or not, update the processing status to false
      if(snum==sessionsToUpload.current.length){
        setProcessing(false);
        // ---------- stop upload on Ok click (OnOKClick) of popup message ------------
        // show ok button popup on upload success
        setshowProgresssBar(false);
        setUploadingSubText(popupMsg);
        setSubTextStyle(subTstyle);
        setShowOkButtonOnUpload(true);

        // update IR session upload status to local list of Pending IR  
       
        let alldata=reportData;
        let store_objI=alldata.findIndex((i)=>{return (i.StoreId==StoreId && i.ScreenName==ScreenName && i.VisitDate==VisitDate)});
        console.log("store_objI",store_objI,StoreId,ScreenName);
       
        if(store_objI>=0){
          let store_obj=alldata[store_objI];
          console.log("store_obj data",store_obj);
       
          store_obj["IRUploadedCount"]=su_num;
          store_obj["isUploaded"]=isUploaded;
          alldata[store_objI]=store_obj;
          setReportData(alldata);
          setrerender(!rerender);
        }
        console.log('Deregister event when last received');
        IRLogin.deRegisterReceiver();
      }
    }

    async function OnOKClick(){
      // stop uploading and hide upload modal 
      setStartUploading(false); // hide upload modal 
      setUploadingSubText(''); // then clear upload modal subtext 
      setTotalUpCount(0); // clear tortal upload count
      UpdateUploadCountLocal(0); // clear uploaded count
      setShowOkButtonOnUpload(false); // hide ok button 
      setSubTextStyle(''); // remove style of subtext in uploading modal 
      
    }
  

    async function UpdateIRUploadStatus(TempSessionId,UnSessionId,TableName1,TableName2,StoreId,IRDetails){
      console.log("UpdateIRUploadStatus");
      // TableName1: IR Upload Table for KPI
      // TableName2: IR Images Table for KPI
      return new Promise((resolve,reject)=>{
          if(TableName1!=null && TableName2!=null && TableName1!='' && TableName2!='')
          {
            db.transaction(async function (txn) {    

              let q=`Update ${TableName1} set UN_SESSION_ID='${UnSessionId}',UPLOAD_STATUS='1',SYNC_STATUS='Synced' where  TEMP_SESSION_ID='${TempSessionId}' and STORE_ID='${StoreId}' `;//VISIT_DATE='${d2}'
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('Updated IR Upload Status',q);
                  let q2=`Update ${TableName2} set UN_SESSION_ID='${UnSessionId}' where  TEMP_SESSION_ID='${TempSessionId}' and STORE_ID='${StoreId}' `;//VISIT_DATE='${d2}' and
                  await txn.executeSql(q2,[],async function (txn2, txnres2) { 
                      console.log('Updated IR Image Status',q2);
                      resolve(true);
                  },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
                  
              },function (txnE,txnerr) { console.log(txnerr);resolve(false); },);
            });  
          }
          else{
            resolve(false);
          }
      }).catch((Err)=>{
          console.log('Error in UpdateIRUploadStatus:',Err);
          return false;
      })
      
                  
      
    }

    async function LogImageUpload(TempSessionId,UnSessionId,message,status,StoreId,StoreName,TableName1,TableName2,IRDetails={}){
      let {IRCategoryName,IRTaskName,IRPhotoType,IRStoreCode,ScreenName}=IRDetails
      const url=props.baseurl+getMethodName(METHODS.UPLOADJSON_METHOD);
      const nowTime=moment().format('HH:mm:ss');
      let ImageCount=await getImageCount(TempSessionId,TableName2);

      ////Replaced special charecter and white space
      let storeTittle = StoreName.replace(`@!%&`, '').replace(' ', '-');
      console.log("storeTittle:",storeTittle,StoreName);
      let d1=new Date();
      let d2=moment(d1).format('MM/DD/YYYY');

      let obj={};
      obj['StoreId']=StoreId;
      obj['Username']=props.UserId;
      obj['VisitDate']=d2;
      obj['InTime']=nowTime;
      obj['TempSessionId']=TempSessionId;
      obj['UnSessionId']=UnSessionId;
      obj['Status']=status;
      obj['Message']=message;
      obj['ImageCount']=ImageCount;
      obj['StoreTitle']=storeTittle;
      obj['StoreCode']=IRStoreCode;
      obj['TaskName']=IRTaskName;
      obj['CategoryName']=IRCategoryName;
      obj['PhotoType']=IRPhotoType;
      obj['KPIType']="";
      obj['ScreenName']=ScreenName;
      obj['UploadType']="New";

                              
      let postData={};
      postData['MID']=0;
      postData['Keys']='IR_UPLOAD_LOG_MSG';
      postData['JsonData']=JSON.stringify(obj);
      postData['UserId']=props.UserId;

      console.log('postData',postData);
        
      return await UploadData2(url,postData)
      .then((res)=>{
          if(res.UploadJsonResult!=null && res.UploadJsonResult=='Success'){
              return true;
          }
          return false;
      })
      .catch((err)=>{
          console.log(err);
          return false;
      });
    }

    async function getImageCount(TempSessionId,TableName2){
      console.log('getImageCount');
      return new Promise((resolve,reject)=>{

        if(TableName2!=null && TableName2!=''){
          db.transaction(async function (txn) {    

              let q=`select DISTINCT TEMP_SESSION_ID,count(IMAGE1) as ImageCount from ${TableName2}  where TEMP_SESSION_ID='${TempSessionId}'  group by TEMP_SESSION_ID `;//VISIT_DATE='${d2}' and 
            
              await txn.executeSql(q,[],async function (txn2, txnres) { 
                  console.log('ImageCount rows:',txnres.rows.length);
                  if(txnres.rows.length>0){
                      let data =txnres.rows.item(0);
                      console.log('data:',data)
                      console.log('Image Count for TempSessionId:',data.ImageCount);
                      resolve(data.ImageCount);
                  }
                  else{
                      resolve(0);
                  }
                  
              },function (txnE,txnerr) { console.log(txnerr);resolve(0); },);
          });  
        }
        else{
          resolve(false);
        }
      }).catch((Err)=>{
          console.log('Error in getImageCount:',Err);
          return 0;
      })
      
                  
      
    }
    
    return ( 
      <Container {...props} pt={0} avoidSafeArea={(Platform.OS=='ios'?true:false)}>
        {processing && <CustomLoader title={ST.Loading+"..."}/>}
        {(startUploading) && <DownloadDataModal title={UploadingText} downloadCount={uploadedCount} totalCount={TotalUpCount} subtitle={UploadingSubText} showProgresssBar={showProgresssBar} showOkButton={showOkButtonOnUpload} OnOKClick={OnOKClick} subTextStyle={subTextStyle}/>}
      
        <CustomHeader {...props}showaddstore={true} title={'IR Pending Images'}/>
        <LinearGradient colors={[PageTheme.$gradient1,PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
        <View style={[customStyle.pageContentWrapper]}>
            <View style={customStyle.ImageTypesPageWrap}>
            <View style={customStyle.ImageTypesLHd}>
                <Text  style={customStyle.ImageTypesLHdText}>{"IR Pending Images Details"}</Text>
            </View>
            </View>
            
          { !props.isDataDownloaded && <NoDataComponent {...props}/>}
          { props.isDataDownloaded==true && 
            <View>
              
              { isDataFound==false && 
                <View style={customStyle.noDataCon}>
                  <Text style={customStyle.noDataText}>{ST.NoDataAvailable}</Text>
                </View>
              }

              {
                isDataFound==true &&
                <ScrollView
                  contentContainerStyle={customStyle.PndIR_scrollViewInner}
                  style={customStyle.PndIR_scrollView}
                >
                  <View style={customStyle.PndIR_MenuCon}>
                    {
                      reportData.length>0 && rerender==rerender && 
                      reportData.map((item,index)=>{
                        let IRUploadedCount=item.IRUploadedCount!=null && item.IRUploadedCount!=''? parseInt(item.IRUploadedCount):0;
                        let isUploaded=item.isUploaded!=null && item.isUploaded!=''? item.isUploaded:false;
                        return(
                          <TouchableOpacity activeOpacity={1} style={[customStyle.storel]} key={index} >
                            <View style={customStyle.storel_card_outer}> 
                                <View style={customStyle.storel_card}>
                                    <View style={customStyle.storel_card_content}>
                                        <Text style={customStyle.storel_card_title}>{item.StoreId}</Text>
                                    </View>                  
                                </View>
                                <View style={customStyle.storel_details}>
                                {item.StoreName!=null && 
                                <View style={customStyle.storel_code}>
                                    <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                                      <Text style={customStyle.storel_codeLbl}>{item.StoreName}</Text>
                                    </View> 
                                </View>
                                }
                                <View style={customStyle.storel_code}>                    
                                    <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                                    <Text style={customStyle.storel_codeLbl}>{'KPI Name:'}</Text>
                                    <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.MenuName}</Text>
                                    </View>
                                </View>
                                <View style={customStyle.storel_code}>                    
                                    <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                                    <Text style={customStyle.storel_codeLbl}>{'Visit Date:'}</Text>
                                    <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr]}>{item.VisitDate}</Text>
                                    </View>
                                </View>
                                <View style={customStyle.storel_code}>                    
                                    <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                                    <Text style={[customStyle.storel_codeLbl,customStyle.PndIR_ItemHighlight]}>{'Pending Images Count:'}</Text>
                                    <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr,customStyle.PndIR_ItemHighlightTxt]}>{item.ImageCount}</Text>
                                    </View>
                                </View>
                                <View style={customStyle.storel_code}>                    
                                    <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                                    <Text style={[customStyle.storel_codeLbl,customStyle.PndIR_ItemHighlight]}>{'Pending Sessions Count:'}</Text>
                                    <Text style={[customStyle.storel_codeText,customStyle.storel_codeTextAddr,customStyle.PndIR_ItemHighlightTxt]}>{item.SessionCount}</Text>
                                    </View>
                                </View>
                                {isUploaded==false && IRUploadedCount!=null && IRUploadedCount>0 &&
                                  <View style={customStyle.storel_code}>                    
                                    <View style={[customStyle.storel_codeCon,customStyle.storel_codeConAddr]}>
                                    <Text style={[customStyle.storel_codeLbl,(IRUploadedCount==0?customStyle.PndIR_ItemHighlightTxt:customStyle.PndIR_ItemHighlightG)]}>{`${IRUploadedCount} out of ${item.SessionCount} IR Sessions Uploaded. !!`}</Text>
                                    </View>
                                  </View>
                                }
                                {isUploaded==true &&
                                  <View style={customStyle.storel_code}>                    
                                    <Ionicons name='checkmark-done-sharp' color='green' size={20}/>
                                    <Text style={[customStyle.storel_usText,{color:'green'}]}>{`All Uploaded`}</Text>
                                  </View>
                                }
                                
                                </View>
                                {isUploaded==false && 
                                <View style={[customStyle.storel_code,customStyle.storel_codeBorderTop,customStyle.mt10]}>                    
                                  <View style={[customStyle.storel_IRBtnWrap]}>
                                    <TouchableOpacity  style={customStyle.storel_uploadIRBtn} onPress={()=>{uploadIRSession(item)}}>
                                      <Text style={customStyle.storel_uploadIRBtnText}>{"Upload IR Session"}</Text>
                                    </TouchableOpacity> 
                                  </View>
                                </View>
                                }
                            </View> 
                          </TouchableOpacity>
                        )
                      })
                    }
                  </View>
                </ScrollView>
              }
                
            </View>
          }
        </View>
        </LinearGradient>

      </Container>   
    ); 
  }
  
  

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