<script setup>

import {BlobReader, BlobWriter, ZipWriter} from "@zip.js/zip.js";

definePageMeta({
  middleware: "auth"
})
const dataStore = useDataStore()
const supabase = useSupabaseClient()
const user = useSupabaseUser()
const toast = useToast()

dataStore.fetchDocuments()

const uploadModalOpen = ref(false)
const uploadInProgress = ref(false)
const fileUploadFormData = ref({
  tags: ["Eingang"],
  path: "",
  tenant: dataStore.currentTenant
})


let tags = dataStore.getDocumentTags

const selectedTags = ref("Eingang")


const filteredDocuments = computed(() => {
  let returnList = []

  returnList =  dataStore.documents.filter(i => i.tags.filter(t => selectedTags.value === t).length > 0)

  //return dataStore.documents.filter(doc => doc.tags.filter(tag => selectedTags.value.find(t => t === tag)).length > 0)
  return returnList

})

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

  await dataStore.uploadFiles(fileUploadFormData.value, document.getElementById("fileUploadInput").files, true)

  uploadModalOpen.value = false;
  uploadInProgress.value = false;
}

const downloadSelected = async () => {
  const bucket = "files";

  let files = []
  dataStore.documents.filter(doc => doc.selected).forEach(doc => files.push(doc.path))

  console.log(files)

  // If there are no files in the folder, throw an error
  if (!files || !files.length) {
    throw new Error("No files to download");
  }

  const promises = [];

// Download each file in the folder
  files.forEach((file) => {
    promises.push(
        supabase.storage.from(bucket).download(`${file}`)
    );
  });

// Wait for all the files to download
  const response = await Promise.allSettled(promises);

// Map the response to an array of objects containing the file name and blob
  const downloadedFiles = response.map((result, index) => {
    if (result.status === "fulfilled") {

      console.log(files[index].split("/")[files[index].split("/").length -1])

      return {
        name: files[index].split("/")[files[index].split("/").length -1],
        blob: result.value.data,
      };
    }
  });

// Create a new zip file
  const zipFileWriter = new BlobWriter("application/zip");
  const zipWriter = new ZipWriter(zipFileWriter, { bufferedWrite: true });

// Add each file to the zip file
  downloadedFiles.forEach((downloadedFile) => {
    if (downloadedFile) {
      zipWriter.add(downloadedFile.name, new BlobReader(downloadedFile.blob));
    }
  });

// Download the zip file
  const url = URL.createObjectURL(await zipWriter.close());
  const link = document.createElement("a");

  link.href = url;
  link.setAttribute("download", "documents.zip");

  document.body.appendChild(link);

  link.click();
}


</script>

<template>
  <UDashboardNavbar
      title="Dokumente"
  >

  </UDashboardNavbar>
  <UDashboardToolbar>
    <template #left>
      <UButton @click="uploadModalOpen = true">Hochladen</UButton>
      <UButton
          @click="downloadSelected"
          :disabled="dataStore.documents.filter(doc => doc.selected).length === 0"
      >Herunterladen</UButton>
    </template>
    <template #right>
      <USelectMenu
          :options="tags"
          v-model="selectedTags"
          class="w-40"
      >
        <template #label>
          {{selectedTags}}
        </template>
      </USelectMenu>
    </template>

  </UDashboardToolbar>

  <div class="scrollList">

    <DocumentList
        :documents="filteredDocuments"
        @selectDocument="(info) => console.log(info)"
    />
  </div>
  <USlideover
      v-model="uploadModalOpen"
  >

    <UCard class="flex flex-col flex-1" :ui="{ body: { base: 'flex-1' }, ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
      <template #header>
        Datei Hochladen
      </template>

      <div class="h-full">
        <UFormGroup
            label="Datei:"
        >
          <UInput
              type="file"
              id="fileUploadInput"
              multiple
          />
        </UFormGroup>

        <UFormGroup
            label="Tags:"
            class="mt-3"
        >
          <USelectMenu
              multiple
              searchable
              searchable-placeholder="Suchen..."
              :options="tags"
              v-model="fileUploadFormData.tags"
          />
        </UFormGroup>
      </div>

      <template #footer>
        <UButton
            v-if="!uploadInProgress"
            class="mt-3"
            @click="uploadFiles"
        >Hochladen</UButton>
        <UProgress
            v-else
            animation="carousel"
        />
      </template>
    </UCard>
  </USlideover>
</template>



<style scoped>


</style>