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

const {items, listData, headers, selected, loading, getItems, editItem, deleteItem, uploadItem} = archive_page();
const trackTypes = trackType(false);
const selectedTrackType = ref();
const selectedFiles = ref([]);
const selectedFilesMetadata = ref([]);
let uploadingFilesNow = ref(false);

watch(selectedFiles, (newFiles) => {
  selectedFilesMetadata.value = newFiles.map(file => ({
    file,
    uploadingNow: false,
    id: null,
    checkAnalyzer: null,
  }));
});

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

const uploadFiles = async () => {
  uploadingFilesNow.value = true;

  const uploadPromises = selectedFilesMetadata.value.map(async (fileToUpload) => {
    fileToUpload.uploadingNow = true;

    const formData = new FormData();
    formData.append('file', fileToUpload.file);
    const response = await uploadItem(formData);

    fileToUpload.id = response?.id;
    fileToUpload.checkAnalyzer = setInterval(
        async () => await checkUploadStatus(fileToUpload),
        500
    );
  });

  await Promise.all(uploadPromises);

  uploadingFilesNow.value = false;
};

const checkUploadStatus = async (file) => {
  return axios.get(`/file/check_upload_status/${file.id}`, {
    params: {
      id: file.id
    }
  }).then(response => {
    if (response.status === 200) {
      if (response.data.import_status === 1) {
        //checkUploadStatus(id)
        console.log('test')
      } else {
        file.uploadingNow = false
        clearInterval(file.checkAnalyzer);
      }
    }
  })
}

</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/*"
          multiple
      ></v-file-input>
      <v-list
          v-if="selectedFiles.length > 0"
      >
        <v-list-item
            v-for="(track, i) in selectedFilesMetadata"
            :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="track.uploadingNow" class="loading">
              mdi-loading
            </v-icon>
            <v-icon v-if="!track.uploadingNow && track.id">
              mdi-check-bold
            </v-icon>
          </template>
          {{ track.file.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 || uploadingFilesNow"
          @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>