import axios from "axios";
import { store } from "../redux/store";

import * as MediaLibrary from "expo-media-library";
import * as ImageManipulator from "expo-image-manipulator";

export const handleLocalUpload = async ({ ev, context }) => {
  const { onError, onSuccess, onProgress, filename, mediaId } = ev;
  const { jobid, invoice_number, vendorid, callbackAfterUpload } = context;
  const bodyshop = store.getState().user.bodyshop;
  var options = {
    headers: {
      "X-Requested-With": "XMLHttpRequest",
      ims_token: bodyshop.localmediatoken,
    },
    onUploadProgress: (e) => {
      if (onProgress) onProgress({ percent: (e.loaded / e.total) * 100 });
    },
  };

  const formData = new FormData();

  formData.append("jobid", jobid);
  if (invoice_number) {
    formData.append("invoice_number", invoice_number);
    formData.append("vendorid", vendorid);
  }
  const imageData = await MediaLibrary.getAssetInfoAsync(mediaId);

  let newFile;
  try {
    newFile = await (await fetch(imageData.localUri || imageData.uri)).blob();
  } catch (error) {
    console.log("blobbing error", error, imageData.localUri || imageData.uri);
  }

  let thumb;
  let fileData = {
    uri: null,
    type: null,
    name: null,
  };
  if (newFile.type === "image/heic") {
    try {
      thumb = await ImageManipulator.manipulateAsync(imageData.uri, [], {
        format: "jpeg",
        base64: true,
        compress: 0.75,
      });
      const name = newFile.data.name.split(".");
      name.pop();
      fileData = {
        uri: thumb.uri,
        type: newFile.type,
        name: name.join("") + ".jpeg",
      };
    } catch (error) {
      console.log(error);
      onError && onError(error.message);
    }
  } else {
    fileData = {
      uri: imageData.localUri || imageData.uri,
      type: newFile.type,
      name: filename,
    };
  }

  formData.append("file", fileData);

  try {
    const imexMediaServerResponse = await axios.post(
      `${bodyshop.localmediaserverhttp}/${
        invoice_number ? "bills" : "jobs"
      }/upload`,
      formData,
      {
        ...options,
      }
    );

    if (imexMediaServerResponse.status !== 200) {
      if (onError) {
        console.log(imexMediaServerResponse);
        onError(
          imexMediaServerResponse.data || imexMediaServerResponse.statusText
        );
      }
    } else {
      onSuccess && onSuccess();
    }

    if (callbackAfterUpload) {
      callbackAfterUpload();
    }
  } catch (error) {
    console.log("Error uploading documents:", onError, error);
    onError && onError(error.message);
  }
};
