import axios from "axios";
import * as MediaLibrary from "expo-media-library";
import mime from "mime";
import { store } from "../redux/store";


axios.interceptors.request.use(
  function (config) {
    config.metadata = { startTime: new Date() };
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  function (response) {
    response.config.metadata.endTime = new Date();
    response.duration =
      response.config.metadata.endTime - response.config.metadata.startTime;
    return response;
  },
  function (error) {
    error.config.metadata.endTime = new Date();
    error.duration =
      error.config.metadata.endTime - error.config.metadata.startTime;
    return Promise.reject(error);
  }
);

export const handleLocalUpload = async ({
  files,
  onError,
  onSuccess,
  onProgress,
  context,
}) => {
  const { jobid } = context;
  const bodyshop = store.getState().user.bodyshop;
  try {
    const options = {
      headers: {
        "Content-Type": "multipart/form-data",
        ims_token: bodyshop.localmediatoken,
      },
      onUploadProgress: (e) => {
        if (onProgress) {
          onProgress({ percent: e.loaded / e.total, loaded: e.loaded });
        }
      },
    };

    const formData = new FormData();

    formData.append("jobid", jobid);

    const filesList = [];
    for (const file of files) {
      const imageData = await MediaLibrary.getAssetInfoAsync(file.id);
      const mimeType = mime.getType(imageData.uri);
      filesList.push({
        uri: imageData.localUri || imageData.uri,
        type: mimeType,
        name: imageData.filename,
      });
      formData.append("file", {
        uri: imageData.localUri || imageData.uri,
        type: mimeType,
        name: imageData.filename,
      });
    }

    //formData.append("file", files);
    formData.append("skip_thumbnail", true);

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

      if (imexMediaServerResponse.status !== 200) {
        if (onError) {
          onError({
            error:
              imexMediaServerResponse.data ||
              imexMediaServerResponse.statusText,
          });
        }
      } else {
        onSuccess &&
          onSuccess({
            duration: imexMediaServerResponse.headers["x-response-time"],
          });
      }
    } catch (error) {

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

    onError && onError({ error: error.message });
  }
};
