import Database from "../../../../../Components/common/DAsyncStorage";

export const addSensorImageData = async (ext, ImageStatus, docName, store) => {
  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

  const sensorData = await Database.get("PISensorDetails");

  console.log(
    "[BACKGROUND] [INFO] . addSensorImageData . sensorData - ",
    sensorData
  );

  if (sensorData) {
    let sensorImageDetails = [...sensorData];
    sensorImageDetails.push({
      attemptCount: attemptCount,
      fileName: fileName,
      latitude: currentLatitude,
      longitude: currentLongitude,
      pose: imageName,
      success: ImageStatus,
      timestamp: new Date().getTime(),
    });
    console.log(
      "[BACKGROUND] [INFO] . addSensorImageData . sensorData [NOT NULL] . sensorImageDetails - ",
      sensorImageDetails
    );
    await setSensorData(sensorImageDetails);
    store.dispatch({
      type: "SENSOR_DETAILS",
      payload: sensorImageDetails,
    });
  } else {
    let sensorImageDetails = [];
    sensorImageDetails.push({
      attemptCount: attemptCount,
      fileName: fileName,
      latitude: currentLatitude,
      longitude: currentLongitude,
      pose: imageName,
      success: ImageStatus,
      timestamp: new Date().getTime(),
    });
    console.log(
      "[BACKGROUND] [INFO] . addSensorImageData . sensorData [NULL] . sensorImageDetails - ",
      sensorImageDetails
    );
    await setSensorData(sensorImageDetails);
    store.dispatch({
      type: "SENSOR_DETAILS",
      payload: sensorImageDetails,
    });
  }
};

const setSensorData = async (dataArr) => {
  const sensorData = Database.get("PISensorDetails");
  if (sensorData) {
    const newArr = [...sensorData, ...dataArr];
    console.log(
      "[BACKGROUND] [INFO] . setSensorData . sensorData [NOT NULL] . newArr - ",
      newArr
    );
    Database.set("PISensorDetails", newArr);
  } else {
    const newArr = [...dataArr];
    console.log(
      "[BACKGROUND] [INFO] . setSensorData . sensorData [NULL] . newArr - ",
      newArr
    );
    Database.set("PISensorDetails", newArr);
  }
};
