<script setup>
import { onMounted, ref, inject, computed } from "vue";

import AudioCard from "../components/AudioCard.vue";
import TotalProgress from "../components/TotalProgress.vue";
import DownloadButton from "../components/DownloadButton.vue";

const axios = inject("axios");

const state_list = ref([]);

const auto_download = ref(false);

onMounted(() => {
  setInterval(() => {
    axios.get("http://localhost:8000/progress").then((resp) => {
      state_list.value = resp.data;
      for (const [i, s] of state_list.value.entries()) {
        if (
          auto_download.value &&
          counter.value.downloading == 0 &&
          s.number &&
          s.title &&
          s.total == 0
        ) {
          axios.post("http://localhost:8000/download", {
            id: i,
            parent_dir: "/home/zhao/Desktop/tmp",
          });
          break;
        }
      }
    });
  }, 500);
});

const counter = computed(() => {
  if (state_list.value.length == 0) {
    return { fetching: true, downloading: false };
  }
  let ready = 0;
  let downloading = 0;
  let finished = 0;
  state_list.value.forEach((s) => {
    if (s.number && s.title && s.total == 0) {
      ready++;
    } else if (s.received < s.total) {
      downloading++;
    } else if (s.total <= s.received && s.total != 0) {
      finished++;
    }
  });
  return { ready: ready, downloading: downloading, finished: finished };
});

const progress_info = computed(() => {
  const total = state_list.value.length;
  const { ready, downloading, finished } = counter.value;
  const fetch_info = "Fetching Information";
  const download_info = "Downloading";
  const finished_info = "Downloads Complete";
  if (total == 0) {
    return { display: fetch_info, finished: 0, total: 0 };
  } else if (ready < total && downloading == 0 && finished == 0) {
    return { display: fetch_info, finished: ready, total: total };
  } else if (finished + downloading + ready == total && finished < total) {
    return { display: download_info, finished: finished + downloading, total: total };
  } else if (finished == total) {
    return { display: finished_info, finished: finished, total: total };
  }
});
</script>

<template>
  <div
    class="vh-100 vw-100 bg-body-secondary overflow-scroll d-flex flex-column position-relative"
  >
    <div class="container overflow-y-scroll flex-grow-1">
      <div class="row g-3 py-3">
        <div
          v-for="state in state_list"
          class="col-12 col-md-10 offset-md-1 col-xl-6 offset-xl-0"
        >
          <AudioCard v-bind="state"></AudioCard>
        </div>
      </div>
    </div>
    <DownloadButton
      @enable-download="auto_download = true"
      v-if="counter.ready == state_list.length"
    ></DownloadButton>
    <TotalProgress v-else v-bind="progress_info"></TotalProgress>
  </div>
</template>
