import * as React from 'react';
import {addDataUrl, FileWithDataUrl} from '@/utils/blob';

export interface UseFileUrlOptions {
  file?: Partial<File>;
}

export const useFileUrl = (options: UseFileUrlOptions) => {
  const { file } = options;
  const [fileWithUrl, setFileWithUrl] = React.useState<Partial<FileWithDataUrl> | undefined>(file);
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    if (!file) {
      if (fileWithUrl) {
        setFileWithUrl(undefined);
      }
      setLoading(false);
      return;
    }

    setFileWithUrl(undefined);
    setLoading(true);
    addDataUrl(file)
      .then((fileWithUrl) => {
        setFileWithUrl(fileWithUrl);
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  }, [file]);

  return React.useMemo(() => ({
    fileWithUrl,
    loading,
  }), [fileWithUrl, loading]);
};

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

export const useFileMetadata = <T extends Partial<FileWithDataUrl>>(options: UseFileMetadataOptions<T>) => {
  const { file, augmentFunction } = options;
  const [fileWithMetadata, setFileWithMetadata] = React.useState<T | undefined>(file as T | undefined);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<Error>();

  React.useEffect(() => {
    if (!file) {
      if (fileWithMetadata) {
        setFileWithMetadata(undefined);
      }
      setLoading(false);
      return;
    }

    setFileWithMetadata(undefined);
    setLoading(true);
    setError(undefined);
    augmentFunction(file)
      .then((theAugmentedFile) => {
        setFileWithMetadata(theAugmentedFile);
        setLoading(false);
      })
      .catch((error) => {
        setFileWithMetadata(file as T);
        setError(error);
        setLoading(false);
      });
  }, [file, augmentFunction]);

  return React.useMemo(() => ({
    fileWithMetadata,
    error,
    loading,
  }), [fileWithMetadata, loading, error]);
};
