import Database from "../../../../../Components/common/DAsyncStorage";
import moment from "moment";
import store from "../../redux/store";

export const initMediaFile = async (
  uri,
  DocumentImageName,
  ext,
  status,
  nextCallback
) => {
  try {
    const networkStatus = store.getState().network.isInternetReachable;
    var mode = networkStatus === true ? "online" : "offline";
    const PIVechicleData = await Database.get("PIVechicleData");
    const activityId = PIVechicleData?.activityId;
    const quoteNumber = PIVechicleData?.quoteNumber;
    const regNumber = PIVechicleData?.licensePlateNumber;
    const activityTypeId = PIVechicleData?.activityTypeId;
    var oldStatus = await Database.get("PIMediaStatus");
    var filteredOldStatus = oldStatus.filter((item) => {
      return item != null;
    });
    console.log(
      "oldStatus oldStatus oldStatus oldStatus : ",
      JSON.stringify(oldStatus, null, "  ")
    );

    const imageObj = [
      {
        status: status, // pending,uploading, uploaded, failed
        uri: uri,
        imageName: DocumentImageName,
        mObjActivityId: activityId,
        mQuoteNumber: quoteNumber,
        mRegNumber: regNumber,
        mActivityTypeId: activityTypeId,
        mMode: mode,
      },
    ];

    const currentActivityObj = [
      {
        activityId: activityId,
        activityTypeId: activityTypeId,
        policyNumber: quoteNumber,
        regNumber: regNumber,
        activityStatus: "PENDING", // PENDING, IN-PROGRESS, COMPLETED  // this is the status of activity not a perticular image
        mode: "ONLINE", // ONLINE, OFFLINE  // have to make dyanamic
        mediaUpload: imageObj,
        date: moment().format("DD MMM YYYY"),
      },
    ];

    var newObj = await addMediaStatusObj(filteredOldStatus, currentActivityObj);
    console.log(
      "DatabaseHelpers - newObj : ",
      JSON.stringify(newObj, null, "  ")
    );
    await Database.set("PIMediaStatus", newObj);
    const PIMediaStatus = await Database.get("PIMediaStatus");
    console.log(
      "DatabaseHelpers - PIMediaStatus initStatusRealm",
      JSON.stringify(PIMediaStatus, null, "  ")
    );
    nextCallback();
  } catch (error) {
    console.log("Error : DatabaseHelper.js : initMediaFile : ", error);
  }
};

const addMediaStatusObj = async (oldStatus, currentActivityObj) => {
  try {
    console.log("DatabaseHelpers - currentActivityObj", currentActivityObj);
    var objectTobeUpdate = currentActivityObj[0]?.mediaUpload[0];
    var newObj;

    console.log("oldStatus", JSON.stringify(oldStatus, null, " "));
    console.log(
      "DatabaseHelpers - currentActivityObj",
      JSON.stringify(currentActivityObj, null, " ")
    );

    // this will excute only if there is no activity in DB
    if (oldStatus == null || oldStatus == undefined) {
      console.log(
        "DatabaseHelpers - oldStatus == null || oldStatus == undefined",
        currentActivityObj
      );
      return currentActivityObj;
    }

    // this will check for activity is present or not
    console.log(
      "DatabaseHelpers - currentActivityObj[0]?.activityId : ",
      currentActivityObj[0]?.activityId,
      JSON.stringify(oldStatus, null, "  ")
    );
    var isActivityAlreadyExist = oldStatus.find((item) => {
      return item.activityId === currentActivityObj[0]?.activityId;
    });

    console.log(
      "DatabaseHelpers - isActivityAlreadyExist",
      !!isActivityAlreadyExist
    );

    if (!!isActivityAlreadyExist) {
      // checking is current image object is already exist or not
      const isImageExist = isActivityAlreadyExist?.mediaUpload?.some((item) => {
        item.imageName === objectTobeUpdate?.imageName;
      });

      // this will check if any image with same name is exist or not
      // var isImageAlreadyExist = isActivityAlreadyExist?.mediaUpload?.filter(
      //   (imageItem) => imageItem.imageName !== objectTobeUpdate.imageItem
      // );

      const isImageAlreadyExist = isActivityAlreadyExist?.mediaUpload?.filter(
        (imageItem) => {
          return imageItem.imageName != objectTobeUpdate.imageName;
        }
      );
      console.log(
        "DataBaseHelper : isImageAlreadyExist",
        JSON.stringify(isImageAlreadyExist, null, "  ")
      );
      var updatedImageWithOutDuplicates = [
        ...isImageAlreadyExist,
        objectTobeUpdate,
      ];
      console.log(
        "DataBaseHelper : isImageAlreadyExist",
        JSON.stringify(updatedImageWithOutDuplicates, null, "  ")
      );
      // newObj is for activity
      newObj = [
        {
          ...isActivityAlreadyExist,
          mediaUpload: updatedImageWithOutDuplicates,
        },
      ];
      console.log(
        "DatabaseHelpers - Activity is present and new Image obj : ",
        JSON.stringify(newObj, null, "  ")
      );
      var nonCurrentActivity = oldStatus.filter((item) => {
        return item.activityId != currentActivityObj[0]?.activityId;
      });
      console.log(
        "DatabaseHelpers -nonCurrentActivity ",
        JSON.stringify(nonCurrentActivity, null, "  ")
      );
      var finalArray = [...nonCurrentActivity, ...newObj];
      return finalArray; // adding previous Activity + current different
    } else {
      console.log(
        "DatabaseHelpers - Activity is not present so Adding  New Activity ",
        JSON.stringify(currentActivityObj, null, "  ")
      );
      return oldStatus.concat(currentActivityObj);
    }
  } catch (error) {
    console.log("Error in addMediaObj ", error);
  }
};

export const makeServiceFailure = (activityId) => {
  updateActivityKey(activityId, "serviceFailure", true);
};

const updateActivityKey = 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;
    }
  });
  await Database.set("PIMediaStatus", nPIMediaStatus);
};

export const findFailureAndReset = async () => {
  const pMediaStatus = await Database.get("PIMediaStatus");
  const mediaStatus = pMediaStatus ?? [];
  log(" findFailureAndReset old pMediaStatus", mediaStatus);
  const newMediaStatus = mediaStatus?.map((activity) => {
    if (activity?.activityStatus !== "COMPLETED") {
      const mediaUpload = activity.mediaUpload;
      const newMediaUpload = mediaUpload?.map((media) => {
        if (media.status === "failed") {
          return {
            ...media,
            status: "pending",
          };
        } else {
          return media;
        }
      });
      return {
        ...activity,
        serviceFailure: false,
        mediaUpload: newMediaUpload,
      };
    } else {
      return activity;
    }
  });
  if (newMediaStatus) {
    log("findFailureAndReset newMediaStatus ", newMediaStatus);
    await Database.set("PIMediaStatus", newMediaStatus);
  } else {
    log(
      "findFailureAndReset newMediaStatus is undefined or null",
      newMediaStatus
    );
  }
};

// const updateFailedStatus = async (activityId, newStatus) => {
//   try {
//     const PIMediaStatus = await Database.get("PIMediaStatus");

//     // getting current activity obj
//     const uploadObj = PIMediaStatus.find((item) => {
//       return item.activityId === activityId;
//     });
//     log("updateFailedStatus uploadObj: " + JSON.stringify(uploadObj));
//     if (uploadObj != null) {
//       var newObj;
//       // updating values of Activity
//       newObj = {
//         ...uploadObj,
//         activityId: activityId,
//         serviceFailure: "false",
//       };
//       // updating value of image
//       var updatedImageInfo = newObj.mediaUpload.map((item) => {
//         if (item.status === "failed") {
//           return {
//             ...item,
//             status: newStatus,
//           };
//         }
//         return item;
//       });

//       // final array = previousImages + currentImages // rcb1 ,rcb2 ,vdo
//       var finalImages = [{ ...uploadObj, mediaUpload: updatedImageInfo }];

//       // for removing last item
//       // did this for removing duplication and old obj
//       PIMediaStatus.pop();

//       log(
//         "updateFailedStatus PIMediaStatus after pop() : ",
//         JSON.stringify(PIMediaStatus, null, "  ")
//       );

//       // adding new updated item
//       var finalArray = PIMediaStatus.concat(finalImages);
//       log(
//         "updateFailedStatus finalArray : ",
//         JSON.stringify(finalArray, null, "  ")
//       );

//       // setting all data in DB
//       await Database.set("PIMediaStatus", finalArray);
//       const alog = await Database.get("PIMediaStatus");
//       console.log("PIMediaStatus", JSON.stringify(alog, null, "  "));
//     }
//   } catch (error) {
//     log("Error in     updateFailedStatus. :", error);
//   }
// };

function log() {
  if (__DEV__) {
    console.log("[DatabaseHelpers] ", ...arguments);
  }
}
