import {Attachment, AttachmentType} from '@interfaces/attachments';

import {MEDIA_MAX_HEIGHT, MEDIA_MIN_HEIGHT} from './constants';

interface CalculateMaxHeightParams {
  attachments: Attachment[];
  maxHeight?: number;
  containerWidth: number;
}

export const calculateMaxHeight = ({
  attachments,
  maxHeight = MEDIA_MAX_HEIGHT,
  containerWidth,
}: CalculateMaxHeightParams): number => {
  let maxScaledHeight = 0;
  let hasVideo = false;

  for (const item of attachments) {
    const hasDimensions = item.width && item.height;

    if (item.type === AttachmentType.VIDEO) {
      hasVideo = true;
    } else if (item.type === AttachmentType.IMAGE && hasDimensions) {
      const scaledHeight = (containerWidth / item.width!) * item.height!;
      maxScaledHeight = Math.max(maxScaledHeight, scaledHeight);
    }
  }

  if (hasVideo) {
    return Math.ceil(Math.min(containerWidth, maxHeight));
  }

  if (maxScaledHeight <= 0) {
    return MEDIA_MIN_HEIGHT;
  }

  return Math.ceil(Math.min(maxScaledHeight, maxHeight));
};
