import {useCallback, useRef} from 'react';
import {useFileUploadStore} from './file-upload-provider';
import {UploadedFile} from '../uploaded-file';
import {UploadStrategyConfig} from './strategy/upload-strategy';
import {openUploadWindow} from '../utils/open-upload-window';

export function useActiveUpload() {
  // use ref for setting ID to avoid extra renders, zustand selector
  // will pick up changed selector on first progress event
  const uploadIdRef = useRef<string>();

  const uploadSingle = useFileUploadStore(s => s.uploadSingle);
  const activeUpload = useFileUploadStore(s =>
    uploadIdRef.current ? s.fileUploads.get(uploadIdRef.current) : null
  );

  const uploadFile = useCallback(
    (file: File | UploadedFile, config?: UploadStrategyConfig) => {
      uploadIdRef.current = uploadSingle(file, config);
    },
    [uploadSingle]
  );

  const selectAndUploadFile = useCallback(
    async (config?: UploadStrategyConfig) => {
      const files = await openUploadWindow({
        types: config?.restrictions?.allowedFileTypes,
      });
      uploadFile(files[0], config);
    },
    [uploadFile]
  );

  return {
    uploadFile,
    selectAndUploadFile,
    percentage: activeUpload?.percentage || 0,
    uploadStatus: activeUpload?.status,
    entry: activeUpload?.entry,
  };
}
