<template>
  <div
    class="q-ma-md"
    test-id="KFileUploaderProgress"
  >
    <span
      class="q-ml-md text-h4"
      test-id="componentTitle"
    >{{ title }}</span>
    <div>
      <div
        v-for="progress, index in listOfProgress"
        :key="index"
        class="row justify-center items-center"
        style="height: 4rem;"
      >
        <div class="full-height column justify-center">
          <q-circular-progress
            test-id="circularProgress"
            show-value
            :indeterminate="!progress.failed && !progress.fulfilled && (progress.progress) !== 100"
            :value="(progress.failed || progress.fulfilled || (progress.progress) === 100) ? 100 : 100"
            :color="getProgressColor(progress)"
            rounded
            size="2rem"
            :thickness="0.3"
            class="q-ma-md"
            font-size="16px"
          >
            <q-icon
              v-if="progress.fulfilled || ((progress.progress) >= 100 && progress.failed === false)"
              test-id="checkIcon"
              name="check"
              color="k-positive"
            />
            <q-icon
              v-else-if="progress.failed"
              test-id="failIcon"
              name="close"
              color="k-negative"
            />
          </q-circular-progress>
        </div>
        <div class="column col justify-center q-mx-md">
          <span
            class="text-h6"
            test-id="title"
          >{{ progress.title }}</span>
          <q-linear-progress
            v-if="progress.progress !== undefined && progress.progress !== null && !isNaN(progress.progress)"
            test-id="linearProgress"
            :color="getProgressColor(progress)"
            :value="(!progress.failed && !progress.fulfilled) ? (progress.progress)/100 : 1"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { KFileUploaderProgressProps, Progress } from './types'
const { title = 'Uploading Files', listOfProgress } = defineProps<KFileUploaderProgressProps>()
import { watch } from 'vue'

// Validate listOfProgress prop
watch(() => listOfProgress, (newList) => {
  try {
    if (!newList) {
      return
    }
    newList.forEach((progress) => {
      if (progress.fulfilled && progress.failed) {
        console.warn('progress cannot be both fulfilled and failed')
      }
      if ((progress.progress < 0) || (progress.progress > 100)) {
        console.warn('progress must be a number between 0 and 100')
      }
    })
  } catch (error) {
    console.error(error)
  }
}, { deep: true })

function getProgressColor (progress: Progress) {
  try {
    if (progress.fulfilled || ((progress.progress) >= 100 && progress.failed === false)) {
      return 'k-positive'
    }
    if (progress.failed) {
      return 'k-negative'
    }
    return 'k-accent'
  } catch (error) {
    console.error(error)
  }
}
</script>

<style></style>
