/*
This file contains the functions that needs to be executed after uploads are successfully executed
in the background
*/
import store from "../../redux/store";
import { getDocumentLast } from "../../common/Services/DocumentLast";
import { genrateSensorFile, unsubscribeSensors } from "../../common/SensorData";
import Database from "../../../../../Components/common/DAsyncStorage";
import {
  errorRecord,
  firebaseAttributes,
} from "../../common/libEventLog/libCrashlytics/libCrashlyticsEvent";
import {
  UELogEvent,
  UELogMessage,
} from "../../common/libEventLog/UserExperior/LibUserExperior";
import { submitPI } from "../../common/Services/submitPI";
// import { useSelector } from "react-redux";
import CONFIGS from "./NotificationsConfig";
import { canGoVideoPi, is2Wflow, isCVFlow } from "../../common/Constants";
import { updateNotificationContent } from "./BackgroundTasksUtils";
import { updateActivityStatus } from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import { makeServiceFailure } from "../SilentUploadV2/DatabaseHelpers";
const stopNotificationUpdate = (callback) => {
  setTimeout(() => {
    //resolve the background task promise
    //removes the notification
    store.dispatch({
      type: "CLEAR_SENSOR_DETAILS_REDUX",
    });
    callback?.();
  }, 15000);
};

const showThankYou = async (flag) => {
  console.log("[INFO] . BackgroundTasksActivityLock . toWithQuote . executed");
  // When submit pi/ document last executes at the background
  // We need a flag to know that the process has been completed
  // Then only we let the user click on go to homepage on thank you screen
  await Database.set("PISuccessFlag", flag);
};

//stopNotification - resolve function of executed promisified background task
export const BackgroundDocumentLast = async (
  { activityID, activityTypeId, licensePlateNumber, quoteNumber },
  activity,
  stopNotification
) => {
  try {
    //Get sensor data info
    // const PISensorDetails = await Database.get("PISensorDetails");
    // console.log(
    //   "[INFO] . BackgroundDocumentLast . PISensorDetails - ",
    //   PISensorDetails
    // );
    const { sensorDataInfo } = store.getState().sensorImageData;
    console.log(
      "[INFO] . BackgroundDocumentLast . PISensorDetails . sensorDataInfo ",
      sensorDataInfo
    );
    //   .sensorDataArray;
    // const { sensorDataInfo } = useSelector((state) => state.sensorImageData);

    console.log(
      "[INFO] . BackgroundTasksActivityLock . ThankYou . documentLast: activityID: " +
        activityID +
        " activityTypeId: " +
        activityTypeId +
        " licensePlateNumber: " +
        licensePlateNumber +
        " quoteNumber: " +
        quoteNumber
    );

    UELogEvent("BackgroundTasksActivityLock . DocumentLast . Started", {
      "Activity Id": JSON.stringify(activityID),
      "Activity Type Id": JSON.stringify(activityTypeId),
      "License Plate Number": JSON.stringify(licensePlateNumber),
      "Quote Number": JSON.stringify(quoteNumber),
      "Sensor Data Info": JSON.stringify(sensorDataInfo),
      isLast: "true",
      source: "DIGITEDGE",
    });
    await genrateSensorFile(
      activityID,
      activityTypeId,
      licensePlateNumber,
      quoteNumber,
      sensorDataInfo,
      activity,
      async () => {
        if (canGoVideoPi(activityTypeId)) {
          try {
            updateNotificationContent(
              CONFIGS.getCustomConfig({
                taskName: "submittinglastdocument",
                taskTitle: "Submitting last document",
                taskDesc: "Please wait while we submit the last document",
              })
            );
            let submitPIRetryCount = 0;
            await getSubmitPIResponse(
              activityID,
              stopNotification,
              submitPIRetryCount,
              licensePlateNumber,
              quoteNumber,
              activity
            );

            //update notification
          } catch (error) {
            console.log(
              "[ERROR] . BackgroundTasksActivityLock . DocumentLast . genrateSensorFile . SubmitPI . Error - ",
              error.message
            );
          }
        }
        // for 2W and CV
        if (is2Wflow(activityTypeId) || isCVFlow(activityTypeId)) {
          updateNotificationContent(
            CONFIGS.getCustomConfig({
              taskName: "submittinglastdocument",
              taskTitle: `Submitting last document for ${
                licensePlateNumber ?? ""
              }${quoteNumber ?? ""}`,
              taskDesc: "Please wait while we submit the last document",
            })
          );
          const DocumentLastData = await getDocumentLast({
            body: {
              activityId: activityID,
              isLast: true,
              source: "DIGITEDGE",
            },
          });

          //update notification
          if (DocumentLastData) {
            updateNotificationContent(
              CONFIGS.getCustomConfig({
                taskName: "documentreceived",
                taskTitle: `${licensePlateNumber ?? ""}${
                  quoteNumber ?? ""
                } documents received`,
                taskDesc:
                  "Thank you for waiting, we have received your documents.",
              })
            );
            showThankYou("true");
            await updateActivityStatus("COMPLETED", activity);
            stopNotificationUpdate(stopNotification);
          } else {
            makeServiceFailure(activityID);
            updateNotificationContent(CONFIGS.AFTER_DOCUMENT_LAST_FAILURE);
            showThankYou("false");
            stopNotificationUpdate(stopNotification);
          }

          UELogEvent("BackgroundTasksActivityLock . DocumentLast . Success", {
            "Document Last Response": JSON.stringify(
              DocumentLastData,
              null,
              "  "
            ),
          });
          console.log(
            "[Info] . BackgroundTasksActivityLock . DocumentLast . genrateSensorFile . DocumentLastData . Response -",
            JSON.stringify(DocumentLastData, null, "  ")
          );
        }
      }
    );
    unsubscribeSensors();
  } catch (error) {
    UELogEvent("BackgroundTasksActivityLock . DocumentLast . Failure", {
      error: JSON.stringify(error),
    });
    firebaseAttributes(error);
    errorRecord(error);
  }
};

const getSubmitPIResponse = async (
  activityID,
  stopNotification,
  submitPIRetryCount,
  licensePlateNumber,
  quoteNumber,
  activity
) => {
  //update notification
  const submitPIResp = await submitPI({
    body: {
      activityId: activityID,
    },
  });
  console.log(
    "getSubmitPIResponse : submitPIResp submitPIResp?.status submitPIResp?.message ",
    submitPIResp,
    submitPIResp?.status === 200,
    submitPIResp?.message === "Success"
  );
  if (
    submitPIResp &&
    submitPIResp?.status === 200 &&
    submitPIResp?.message === "Success"
  ) {
    console.log(
      "in getSubmitPIResponse Before : updateActivityStatus ",
      activity
    );
    await updateActivityStatus("COMPLETED", activity);
    console.log(
      "in getSubmitPIResponse Before : updateActivityStatus ",
      activity
    );
    showThankYou("true");
    updateNotificationContent(
      CONFIGS.getCustomConfig({
        taskName: "documentreceived",
        taskTitle: `${licensePlateNumber ?? ""}${
          quoteNumber ?? ""
        } Documents Received`,
        taskDesc: "Thank you for waiting, we have received your documents.",
      })
    );
    stopNotificationUpdate(stopNotification);
  } else {
    if (submitPIRetryCount < 2) {
      UELogEvent("Submit PI Retry", {
        "Retry Count": `${submitPIRetryCount}`,
      });
      submitPIRetryCount++;
      getSubmitPIResponse(
        activityID,
        stopNotification,
        submitPIRetryCount,
        licensePlateNumber,
        quoteNumber
      );
    } else {
      makeServiceFailure(activityID);
      updateNotificationContent(CONFIGS.AFTER_SUBMIT_PI_FAILURE);
      showThankYou("false");
      stopNotificationUpdate(stopNotification);
    }
  }

  console.log(
    "[INFO] . BackgroundTasksActivityLock . DocumentLast . genrateSensorFile . SubmitPI . getSubmitPIResponse . response -  ",
    JSON.stringify(submitPIResp, null, "  ")
  );
};

export const addSensorImageData = async (ext, ImageStatus, docName) => {
  let sensorImageDetails = [];
  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(),
  });

  store.dispatch({
    type: "SENSOR_DETAILS",
    payload: sensorImageDetails,
  });
};
