import cleanAxios from "../../utils/CleanAxios";
import { store } from "../../redux/store";
import { addMediaForJob } from "../../redux/media/media.actions";
import normalizeUrl from "normalize-url";
import i18n from "i18next";

export const handleUpload = async ({ ev, context, notification }) => {
  const { onError, onSuccess, onProgress, file } = 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);
  }
  formData.append("file", file);

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

  if (imexMediaServerResponse.status !== 200) {
    if (onError) {
      onError(imexMediaServerResponse.statusText);
    }
  } else {
    onSuccess && onSuccess(file);
    if (notification) {
      notification.success({
        key: "docuploadsuccess",
        title: i18n.t("documents.successes.insert")
      });
    } else {
      console.error("No notification context found in document local upload utility.");
    }
    store.dispatch(
      addMediaForJob({
        jobid,
        media: imexMediaServerResponse.data.map((d) => {
          return {
            ...d,
            selected: false,
            src: normalizeUrl(`${bodyshop.localmediaserverhttp}/${d.src}`),
            ...(d.optimized && {
              optimized: normalizeUrl(`${bodyshop.localmediaserverhttp}/${d.optimized}`)
            }),
            thumbnail: normalizeUrl(`${bodyshop.localmediaserverhttp}/${d.thumbnail}`)
          };
        })
      })
    );
  }

  if (callbackAfterUpload) {
    callbackAfterUpload();
  }
};
