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

const FileUploadContext = React.createContext();

export const FileUploadProvider = ({ children }) => {
  const [file, setFile] = useState(null);
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);
  const [status, setStatus] = useState(null);
  const [cancelUpload, setCancelUpload] = 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) => {
    try {
      if (!files || files.length === 0) throw new Error("No file provided");

      const file = files[0].file;
      const filename = file.name;
  
      setUploading(true);
      setProgress(0);
      setStatus(`Uploading ${filename}`);
      setCancelUpload(getCancelToken());
      
      const result = await uploadFile(file, setProgress, cancelUpload);
      const url = ((result && result.url) ? result.url : "No URL available");
      setStatus(`Uploaded ${filename}\n${url}`);
      setCancelUpload(null);
      setProgress(100);
    }
    catch (e) {
      setStatus(`Error occured: ${e.message}`);
    }
  };

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

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