
import React, { useContext, useMemo } from 'react';
import UploadControllerFactory from 'upload-controller-factory';

const UploadContext = React.createContext(null as any);
const PreviewContext = React.createContext(null as any);

export function useUploadController() {
  return useContext(UploadContext);
}

export function usePreviewComponent() {
  return useContext(PreviewContext);
}

type UploadProviderProps = {
  uploader: any;
  preview?: any;
  fields?: any;
  children: React.ReactNode;
};

export default function UploadProvider({ uploader, preview, fields, children }: UploadProviderProps) {
  const uploadController = useMemo(() => {
    const obj = UploadControllerFactory({
      uploader,
      fields
    });

    obj.uploader = uploader;
    return obj;
  }, [uploader, fields]);

  return <UploadContext.Provider value={uploadController}>
    <PreviewContext.Provider value={preview}>
      { children }
    </PreviewContext.Provider>
  </UploadContext.Provider>;
}
