import { POSE_DETECTION } from "../../Api/ApiUrls";
import { errorRecord } from "../../common/libEventLog/libCrashlytics/libCrashlyticsEvent";
import {
  UEEndTimer,
  UELogEvent,
  UELogMessage,
  UEStartTimer,
} from "../../common/libEventLog/UserExperior/LibUserExperior";

export const poseDetection = async (body) => {
  console.log(
    "[Info] . poseDetection.js . poseDetection started  - ",
    "URL",
    POSE_DETECTION,
    "BODY",
    JSON.stringify(body, null, "  ")
  );

  let requestOptions = {
    method: "POST",
    body: body,
    redirect: "follow",
  };

  try {
    const response = await fetch(POSE_DETECTION, requestOptions);
    if (response.status === 200) {
      const poseDetectionText = await response.text();
      console.log(
        "[Info] . poseDetection.js . poseDetectionText - ",
        poseDetectionText
      );
      console.log(
        "[Info] . poseDetection.js . poseDetectionText - parse",
        JSON.parse(poseDetectionText)
      );
      return JSON.parse(poseDetectionText);
    } else {
      throw new Error(response.text);
    }
  } catch (e) {
    console.log("[Erorr] . poseDetection.js . Error - ", e.message);
  }
};

// instructions
// export const poseDetection = async ({ body }) => {
//   UELogEvent("poseDetection API Execution Started", {
//     payload: JSON.stringify(body),
//   });
//   try {
//     console.log("POSE API ->", POSE_DETECTION);
//     UEStartTimer(POSE_DETECTION);

//     const res = await fetch(`${POSE_DETECTION}`, {
//       method: "POST",
//       headers: {
//         "Content-Type": "multipart/form-data",
//       },
//       body,
//     });
//     let data = await res.text();
//     if (res.status !== 200) {
//       UELogMessage(`Status ${res.status}`, {
//         status: res.status,
//         error: JSON.stringify(data?.error),
//       });
//       throw new Error(data?.error);
//     }

//     UELogEvent("poseDetection API Execution Ended in Try", {
//       response: JSON.stringify(data),
//     });

//     UEEndTimer(POSE_DETECTION);

//     return data;
//   } catch (err) {
//     UELogEvent("poseDetection API Execution Ended in Catch", {
//       error: JSON.stringify(err),
//     });

//     errorRecord(err);
//     console.log("FROM POSE DETECTION ", err);
//   }
// };

// export const poseDetection = (body) => {
//   var xhr = new XMLHttpRequest();
//   xhr.withCredentials = true;
//   xhr.addEventListener("readystatechange", function() {
//     if (this.readyState === 4) {
//       console.log("Pose Detection Response Text", this.responseText);
//       return this.responseText;
//     }
//   });
//   xhr.open("POST", POSE_DETECTION);
//   xhr.send(body);
// };
