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";
import store from "react-native-digitcamera/src/redux/store";
import { NamedModal } from "react-native-digitcamera/src/common/GlobalModal";
import {
  canCreateActivityId,
  updateActivityId,
} from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import { startOfflineBackgroundUpload } from "react-native-digitcamera/src/Screens/SilentUpload/SilentUploadUtils";
import { initMediaFile } from "react-native-digitcamera/src/Screens/SilentUploadV2/DatabaseHelpers";
var sensorImageDetails = [];

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

  const AppLoginStatus = await Database.get("AppLoginStatus");
  try {
    console.log("**** CreateActivityId called");
    if (
      canCreateActivityId(activityDetails?.activityId) ||
      activityDetails?.activityId == undefined ||
      activityDetails?.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 = activityDetails?.regNumber;
      var quoteNumber = activityDetails?.policyNumber;
      var activityTypeId = activityDetails?.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 });

      /**
       * If getActivityId failed
       * then show failure modal
       */
      if (!activityData) {
        updateActivityStatus(
          activityDetails.activityId,
          "serviceFailure",
          true
        );
        await Database.set("PIReUploadFailed", "true");
        return;
      }

      if (activityData.flag === "Manual Inspection") {
        store.dispatch({
          type: "GLOBAL_MODAL_SHOW",
          payload: NamedModal.MANUAL_INSPECTION,
        });
        return;
      }

      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;
        }
      });

      // update activityid in PIMediaStatus database
      console.log(
        "updateActivityId activityDetails : ",
        activityDetails,
        activityData?.activityID
      );

      // only update current activity data in PIVechicleData
      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: "",
      });
      const PIVechicleData = await Database.get("PIVechicleData");
      console.log(
        "PIVechicleData : in CreateActivity.js : after creating new Activity ",
        PIVechicleData
      );

      await updateActivityId(activityDetails, activityData?.activityID);

      var log_PIVechicleData = await Database.get("PIVechicleData");
      console.log(
        "PIVechicleData CreateActivityId.js ",
        JSON.stringify(log_PIVechicleData, null, "  ")
      );
      updateReduxCallback();
    }

    // upload data

    var PIMediaStatus = await Database.get("PIMediaStatus");
    var inProgressArray = PIMediaStatus.filter((activity) => {
      console.log("activity.activityStatus", activity.activityStatus);
      return activity.activityStatus === "IN-PROGRESS";
    });

    // console.log("inProgressArray  : ", inProgressArray);
    // inProgressArray.forEach((activity) => {
    //   console.log("activity?.mediaUpload.length", activity?.mediaUpload.length);
    //   if (activity?.mediaUpload.length > 0) {
    //     activity.mediaUpload.forEach((images) => {
    //       if (images.status == "pending") {
    //         console.log(
    //           "****  ****  Offline Images   ",
    //           JSON.stringify(images?.imageName, null, "  ")
    //         );
    //         let uri = images?.uri;
    //         let imageName = images?.imageName;
    //         let ext = imageName == "VDO" ? ".mp4" : ".jpg";

    //         initMediaFile()

    //         // const isUploading =
    //         //   store
    //         //     .getState()
    //         //     .uploadingData.data.find(
    //         //       (item) => item.imageName === imageName
    //         //     ) !== undefined;

    //         // console.log(
    //         //   `[CREATE ACTIVITY ID] [INFO] ${imageName} - isUploading ${isUploading}`
    //         // );

    //         // if (!isUploading) {
    //         //   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);
  }
};

// this function adds "value" agains a "key"  to a Activity in PIMediaStatus DB

// I'm using this to update if any of the service fails
//  /preinpsection & /instruction if failed
// then serviceFailure = true
const updateActivityStatus = async (activityId, key, value) => {
  const pMediaStatus = await Database.get("PIMediaStatus");
  const nPIMediaStatus = pMediaStatus.map((item) => {
    if (item.activityId === activityId) {
      const newObj = item;
      newObj[key] = value;
      return newObj;
    } else {
      return item;
    }
  });
  Database.set("PIMediaStatus", nPIMediaStatus);
};

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(),
  });
};
