import * as React from 'react';

export interface UseAugmentedFileOptions<T extends Partial<File> = Partial<File>> {
  file?: File;
  augmentFunction: (file: File) => Promise<T>;
}

export const useAugmentedFile = <T extends Partial<File>>(options = {} as UseAugmentedFileOptions<T>) => {
  const { file, augmentFunction } = options;
  const [augmentedFile, setAugmentedFile] = React.useState<T>();
  const [error, setError] = React.useState<Error>();

  React.useEffect(() => {
    if (!file) {
      return;
    }

    setError(undefined);
    augmentFunction(file)
      .then((theAugmentedFile) => {
        setAugmentedFile(theAugmentedFile);
      })
      .catch((error) => {
        setError(error);
      });
  }, [file, augmentFunction]);

  return React.useMemo(() => ({
    augmentedFile: (augmentedFile ?? file) as T | undefined,
    error,
  }), [augmentedFile, file, error]);
};
