import { useEffect, useState } from "react";
import {
  getImageUrlWithCDN,
  transformImageFromUrl,
  TransformationParams,
} from "utils/photo";

export const useImage = (
  imageUrl: string,
  transformationParams?: TransformationParams
): string => {
  const [croppedImageUrl, setCroppedImageUrl] = useState<string | undefined>();

  useEffect(() => {
    const fetchCroppedImageUrl = async () => {
      if (!imageUrl) {
        return;
      }

      const newCroppedImageUrl = await transformImageFromUrl(
        imageUrl,
        transformationParams
      );
      setCroppedImageUrl(newCroppedImageUrl);
    };

    fetchCroppedImageUrl();
  }, [imageUrl, transformationParams]);

  if (croppedImageUrl) {
    return croppedImageUrl;
  }

  return getImageUrlWithCDN(imageUrl);
};
