import React, { useContext, useState } from "react";
import { uploadFile, getCancelToken } from "../../services/uploadFile";

const FileUploadContext = React.createContext();

export const FileUploadProvider = ({ children }) => {
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [status, setStatus] = useState(null);
  const [cancelUpload, setCancelUpload] = useState(null);
  const [linkURL, setLinkURL] = useState(null);

  const done = () => {
    setCancelUpload(null);
    setUploading(false);
    setProgress(0);
  };

  const cancel = async () => {
    if (cancelUpload && progress < 100) {
      cancelUpload.cancel();
      setStatus("Upload cancelled");
    }
    done();
  };

  const upload = async (files, accessToken) => {
    try {
      if (!files || files.length === 0) throw new Error("File required");
      if (!accessToken || accessToken.length === 0) throw new Error("Access token required")
      const file = files[0].file;
      const filename = file.name;
  
      setUploading(true);
      setLinkURL(null);
      setProgress(0);
      setStatus(`Uploading ${filename}`);
      setCancelUpload(getCancelToken());
      
      const { data } = await uploadFile(file, accessToken, setProgress, cancelUpload);
      if (data.message) throw new Error(`${data.error}. ${data.message}`);
      const url = ((data && data.link && data.link.link) ? data.link.link : "No URL available");
      setLinkURL(url);
      setStatus(`Uploaded ${filename}`);
      setCancelUpload(null);
      setProgress(100);
    }
    catch (e) {
      setStatus(`Error occured: ${e.message}`);
      setProgress(-1);
    }
  };

  return (
    <FileUploadContext.Provider value={{
      uploading,
      progress,
      status,
      linkURL,
      upload,
      cancel,
    }}>
      {children}
    </FileUploadContext.Provider>
  );
};

export const useFileUploadContext = () => useContext(FileUploadContext);
