<script setup lang="ts">
import axios from "axios";
import {ref, reactive} from "vue";
import { trackType } from "@/composables/content/track_type.ts";
import {archive} from "@/composables/content/archive.js.ts";

const { items, listData, headers, selected, loading, getItems, editItem, deleteItem, uploadItem } = archive();
const trackTypes = trackType(false);
const check_analyzer = ref([]);
const selectedTrackType = ref();
const selectedFiles = ref([]);
const filesUploading = reactive({
  is_uploading: false,
  uploading: [],
  uploaded: []
});

// watch(filesUploading, async (newFiles, oldFiles) => {
//   console.log(newFiles);
// })

 const removeUnacceptedFiles = (files) => {
   files = files.map(el => {
     return el;
   })
   selectedFiles.value = files.filter(el => el.type.split('/', 1) == 'audio')
 }

const uploadFiles = () => {
  selectedFiles.value.forEach( async (el, key) => {
    //ToDo: check if a track already exists
    filesUploading.is_uploading = true
    selectedFiles.value[key].id = 0

    const formData = new FormData()
    formData.append('file', el)
    const response = await uploadItem(formData);
    console.log(response)
    selectedFiles.value[key].id = response.id;
    filesUploading.uploading.push(response.id);
    check_analyzer.value[response.id] = setInterval(
        () => checkUploadStatus(response.id),
        200
    )
  })
}

const checkUploadStatus = (id) => {
  return axios.get(`/file/check_upload_status/${id}`, {
    params: {
      id: id
    }
  }).then(response => {
    console.log(response)
    if (response.status === 200) {
      console.log(response.data)
      if (response.data.import_status === 1) {
        //checkUploadStatus(id)
        console.log('ancora nu')
        console.log(check_analyzer.value[id])
      } else {
        console.log('andata')
        filesUploading.uploaded.push(id)
        const uploading_index = filesUploading.uploading.indexOf(id)
        const check_analyzer_index = check_analyzer.value.indexOf(id)
        if (uploading_index > -1) {
          filesUploading.uploading.splice(uploading_index, 1)
        }
        if (check_analyzer_index > -1) {
          check_analyzer.value.splice(check_analyzer_index, 1)
        }

        /**
         * ToDo: understand why clearInterval doesn't work, or find another way to
         * check the status
         */
        clearInterval(check_analyzer.value[id]);
        console.log(check_analyzer.value[id])
      }
    }
  })
}
</script>

<template>
  <v-card>
    <v-card-title>Carica uno o più file e scegli la tipologia di traccia da associarci</v-card-title>
    <v-card-text>
      <v-select
          v-model="selectedTrackType"
          :items="trackTypes.trackTypes.value"
          item-title="type_name"
          label="Seleziona la tipologia di tracce che vuoi caricare"
          return-object
      ></v-select>
      <v-file-input
          v-model="selectedFiles"
          @update:model-value="removeUnacceptedFiles"
          label="Seleziona i file da caricare"
          accept="audio/*"
          item-title=""
          multiple
      ></v-file-input>
      <v-list
          v-if="selectedFiles.length > 0"
      >
        <v-list-item
            v-for="(track, i) in selectedFiles"
            :key="i"
            :value="track"
            rounted="xl"
            color="accent"
            aria-selected="true"
            class="text-accent v-list-item--active mb-1"
        >
          <template v-slot:append>
            <v-icon
                v-if="filesUploading.uploading.includes(track?.id)"
                class="loading"
            >
              mdi-loading
            </v-icon>
            <v-icon
                v-if="filesUploading.uploaded.includes(track?.id)"
            >
            mdi-check-bold
          </v-icon>
          </template>
          {{ track.name }}
        </v-list-item>
      </v-list>
      {{selectedTrackType}}
    </v-card-text>
    <v-card-actions>
      <v-btn
          color="primary"
          size="large"
          type="submit"
          variant="elevated"
          :disabled="selectedFiles.length === 0 || filesUploading.is_uploading"
          @click="uploadFiles"
      >Carica</v-btn>
    </v-card-actions>
  </v-card>
</template>

<style scoped>
.loading {
  animation: loading 1.2s linear infinite;
}

@keyframes loading {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>