import { Alert } from "react-native";
import { is2Wflow } from "react-native-digitcamera/src/common/Constants";
import { getActivityid } from "react-native-digitcamera/src/common/Services/getActivityid";
import UploadFile from "react-native-digitcamera/src/Screens/UploadFile";
import { async } from "validate.js";
import Database from "../../../../../Components/common/DAsyncStorage";
var sensorImageDetails = [];


export const CreateActivityId= async(updateReduxCallback, addSensorDataCallback)=>{
  var vechicleData = await Database.get("PIVechicleData");

  const AppLoginStatus = await Database.get("AppLoginStatus");
    try {
      console.log("**** CreateActivityId called");
     if(vechicleData?.activityId==0||vechicleData?.activityId==undefined||vechicleData?.activityId==null) {
        //API call
        console.log("In if     ");
        const { getUserDetails } = require("../../common/Who");
       await getUserDetails();
        const {
          emailId,
          name,
          phoneNo,
          panHolderName,
          panNo,
          agentNumber,
        } = require("../../common/Who");
      const USERTYPE = AppLoginStatus?.userType;
      let body;
       var registrationNumber = vechicleData?.licensePlateNumber
       var quoteNumber = vechicleData?.quoteNumber
       var activityTypeId = vechicleData?.activityTypeId
       var toTutorial = vechicleData?.toTutorial
       var toWithQuote = vechicleData?.toWithQuote

        if (USERTYPE === "Customer") {
          body = {
            activityTypeId: activityTypeId,
            customerDetailData: {
              emailId: emailId,
              name: name,
              phoneNo: phoneNo,
            },
            licensePlateNumber: registrationNumber,
            previousPolicyExpired: true,
            quoteNumber: quoteNumber,
          };
        } else if (USERTYPE === "DealerOrAgent") {
          body = {
            activityTypeId: activityTypeId,
            customerDetailData: {
              emailId: emailId,
              name: name,
              phoneNo: phoneNo,
              panHolderName: panHolderName,
              panNo: panNo,
            },
            agentId: agentNumber,
            licensePlateNumber: registrationNumber?.value,
            previousPolicyExpired: true,
            quoteNumber: quoteNumber,
          };
        }

       var activityData = await getActivityid({ body });
      registrationNumber =
          activityData?.additionalActivitiesList.filter((item) => {
            if (item.key == "Registration Number") {
              return item;
            }
          });
        let userNCB = activityData?.additionalActivitiesList.filter(
          (item) => {
            if (item.key == "User NCB") {
              return item;
            }
          }
        );
          await Database.update("PIVechicleData", {
            activityId: activityData?.activityID,
            activityTypeId: activityData?.activityTypeId,
            licensePlateNumber:
              registrationNumber === undefined
                ? ""
                :registrationNumber[0]?.value,
            toWithQuote: toWithQuote,
            toTutorial: toTutorial,
            quoteNumber: quoteNumber,
            ncb:
              userNCB === undefined || userNCB.length == 0
                ? 0
                : Number(userNCB[0].value),
            vechicleType: "",
          });
          console.log("PIVechicleData CreateActivityId.js ",JSON.stringify(activityData,null,"  "));
        updateReduxCallback()
        }

        let offlineImageData = await Database.get("PIOfflineVechicleData");
        let PIVechicleData = await Database.get("PIVechicleData");
        console.log(" **** CreateActivityId.js PIVechicleData ",JSON.stringify(PIVechicleData,null,"  "));
        console.log(" **** CreateActivityId.js PIOfflineVechicleData ",JSON.stringify(offlineImageData,null,"  "));
        if(offlineImageData!=null)
        {
        JSON.parse(offlineImageData?.dataTobeUploaded).map(
          (dataTobeUploaded) => {
            if(dataTobeUploaded.status!="uploaded")
            {
            console.log("****  ****  Offline Images   ",JSON.stringify(dataTobeUploaded?.imageName,null,"  "));
            let uri = dataTobeUploaded?.uri;
            let imageName = dataTobeUploaded?.imageName;
            let ext = imageName == "VDO" ? ".mp4" : ".jpg";
             UploadFile(
              uri,
              imageName,
              ext,
              () => {
                props.navigation.navigate("WithQuote");
              },
             async () => {
               await addSensorImageData(ext, true,imageName);
               addSensorDataCallback(sensorImageDetails)
              },
             async () => {
                addSensorImageData(ext, false,imageName);
                await addSensorDataCallback(sensorImageDetails)
              }
            );
          }
        }
        );
        }
      } catch (error) {
        console.log("Error in CreateActivityId.js ",error);
      }
    }

const addSensorImageData = async(ext, ImageStatus,docName) => {
  const PILocation = await Database.get("PILocation");
  const PIRetryCount = await Database.get("PIRetryCount");
  let offlineImageData = await Database.get("PIOfflineVechicleData");
  var currentLatitude = PILocation?.lat;
var currentLongitude = PILocation?.long;
var activityId=offlineImageData?.activityId
   let imageName = docName;
   var attemptCount = PIRetryCount?.retryCount + 1;
   var fileName = activityId + "_" + imageName + ext;
   //adding sensor data
   sensorImageDetails.push({
     attemptCount: attemptCount,
     fileName: fileName,
     latitude: currentLatitude,
     longitude: currentLongitude,
     pose: imageName,
     success: ImageStatus,
     timestamp: new Date().getTime(),
   });

   };