<!-- 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
        variant="secondary"
        :disabled="!!props.error"
        :title="props.url"
        @click="download.triggerBrowserDownload"
      >
        {{ $t('g.downloadWithSize', { size: fileSize }) }}
      </Button>
    </div>
    <div>
      <Button variant="secondary" :disabled="!!props.error" @click="copyURL">
        {{ $t('g.copyURL') }}
      </Button>
    </div>
  </div>
</template>

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

import Button from '@/components/ui/button/Button.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>
