import {
  ImageVaultAsset,
  ImageVaultAssetResponse,
} from "@/types/components/imageVault"

export function insertResponseToImageVaultAsset(
  response: ImageVaultAssetResponse
): ImageVaultAsset {
  const alt = response.Metadata?.find((meta) =>
    meta.Name.includes("AltText_")
  )?.Value

  const caption = response.Metadata?.find((meta) =>
    meta.Name.includes("Title_")
  )?.Value

  const mediaConversion = response.MediaConversions[0]
  const aspectRatio =
    mediaConversion.FormatAspectRatio ||
    mediaConversion.AspectRatio ||
    mediaConversion.Width / mediaConversion.Height

  return {
    url: mediaConversion.Url,
    id: response.Id,
    meta: {
      alt,
      caption,
    },
    title: response.Name,
    dimensions: {
      width: mediaConversion.Width,
      height: mediaConversion.Height,
      aspectRatio,
    },
    focalPoint: response.FocalPoint || { x: 50, y: 50 },
  }
}

export function makeImageVaultImage(image: any) {
  return image && !!Object.keys(image).length
    ? insertResponseToImageVaultAsset(image as ImageVaultAssetResponse)
    : undefined
}
