import { useState, useEffect } from 'react';

import { getDimensions } from 'src/services/attachments';
import { FileTypes } from 'src/types/attachments';
import { getBlob } from 'src/utils/files';

import { MediaBaseProps } from '../MediaBase';

export const useGetDimensionsOfMediaFile = (
  props: MediaBaseProps,
  type?: FileTypes,
) => {
  const [width, setWidth] = useState(props.mediaWidth || 0);
  const [height, setHeight] = useState(props.mediaHeight || 0);

  useEffect(() => {
    (async () => {
      const hasPreCalculatedDimensions = props.mediaWidth || props.mediaHeight;

      if (
        !hasPreCalculatedDimensions &&
        'source' in props.media &&
        props.media.source
      ) {
        const blob = await getBlob(props.media.source);
        const dimensions = await getDimensions(blob);
        setWidth(dimensions.width);
        setHeight(dimensions.height);
      }
    })();
  }, [props.media]);

  return {
    mediaWidth:
      type === FileTypes.IMAGE ? props.mediaWidth || width : props.mediaWidth,
    mediaHeight:
      type === FileTypes.IMAGE
        ? props.mediaHeight || height
        : props.mediaHeight,
  };
};
