<!-- A file download button with a label and a size hint -->
<template>
  <div class="flex flex-row items-center gap-2">
    <div>
      <div>
        <span :title="hint">{{ label }}</span>
      </div>
      <Message
        v-if="props.error"
        severity="error"
        icon="pi pi-exclamation-triangle"
        size="small"
        variant="outlined"
        class="my-2 h-min max-w-xs px-1"
        :title="props.error"
        :pt="{
          text: { class: 'overflow-hidden text-ellipsis' }
        }"
      >
        {{ props.error }}
      </Message>
    </div>
    <div>
      <Button
        :label="$t('g.download') + ' (' + fileSize + ')'"
        size="small"
        outlined
        :disabled="!!props.error"
        :title="props.url"
        @click="download.triggerBrowserDownload"
      />
    </div>
    <div>
      <Button
        :label="$t('g.copyURL')"
        size="small"
        outlined
        :disabled="!!props.error"
        @click="copyURL"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import Button from 'primevue/button'
import Message from 'primevue/message'
import { computed } from 'vue'

import { useCopyToClipboard } from '@/composables/useCopyToClipboard'
import { useDownload } from '@/composables/useDownload'
import { formatSize } from '@/utils/formatUtil'

const props = defineProps<{
  url: string
  hint?: string
  label?: string
  error?: string
}>()

const label = computed(() => props.label || props.url.split('/').pop())

const hint = computed(() => props.hint || props.url)
const download = useDownload(props.url)
const fileSize = computed(() =>
  download.fileSize.value ? formatSize(download.fileSize.value) : '?'
)
const copyURL = async () => {
  await copyToClipboard(props.url)
}

const { copyToClipboard } = useCopyToClipboard()
</script>
