<template>
  <v-fade-transition>
    <div
      v-if="infos.length"
      class="download-center"
    >
      <v-card
        elevation="10"
        class="pa-3"
      >
        <div class="text-subtitle-1 mb-2">Downloads</div>
        <div
          v-for="info in infos"
          :key="info.Id"
          class="d-flex align-center ga-3 mb-3"
        >
          <div class="flex-grow-1">
            <div class="text-body-2">{{ label(info) }}</div>
            <div class="text-caption mb-1">{{ detail(info) }}</div>
            <v-progress-linear
              :indeterminate="isIndeterminate(info)"
              :model-value="pct(info)"
            />
          </div>
          <div class="d-flex ga-1">
            <v-btn
              size="small"
              icon="pause"
              @click="pause(info)"
            />
            <v-btn
              size="small"
              icon="play_arrow"
              @click="resume(info)"
            />
            <v-btn
              size="small"
              icon="close"
              @click="cancel(info)"
            />
          </div>
        </div>
      </v-card>
    </div>
  </v-fade-transition>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useDownloadStore } from '@/stores/download.store';

const store = useDownloadStore();
const { infos } = storeToRefs(store);

function pct(info: any) {
  const p = Math.round(info.Percentage ?? 0);
  return p < 0 ? 0 : p > 100 ? 100 : p;
}

function isIndeterminate(info: any) {
  return (
    info.Total === 0 &&
    (info.Percentage == null || Number.isNaN(info.Percentage))
  );
}

function label(info: any) {
  return (
    info.Name ||
    info.Title ||
    info.FileName ||
    info.filename ||
    (info.Id ?? info.id)
  );
}

function detail(info: any) {
  if (info.Message) return info.Message;
  if (info.Total && info.Completed != null)
    return `${info.Completed} / ${info.Total}`;
  return '';
}

function pause(info: any) {
  store.requestPause(info.Id ?? info.id);
}
function resume(info: any) {
  store.requestResume(info.Id ?? info.id);
}
function cancel(info: any) {
  store.requestCancel(info.Id ?? info.id);
}
</script>

<style scoped>
.download-center {
  position: absolute;
  bottom: 16px;
  left: 16px;
  right: 16px;
  z-index: 6;
}
</style>
