<script setup>


import {BlobReader, BlobWriter, ZipWriter} from "@zip.js/zip.js";
import {useSupabaseSelectSingle} from "~/composables/useSupabase.js";
import DocumentDisplayModal from "~/components/DocumentDisplayModal.vue";
import DocumentUploadModal from "~/components/DocumentUploadModal.vue";
import dayjs from "dayjs";

definePageMeta({
  middleware: "auth"
})

defineShortcuts({
  /*'/': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    document.getElementById("searchinput").focus()
  },*/
  '+': () => {
    //Hochladen
    uploadModalOpen.value = true
  },
  'Enter': {
    usingInput: true,
    handler: () => {
      let entry = renderedFileList.value[selectedFileIndex.value]

      if(entry.type === "file") {
        showFile(entry.id)
        console.log(entry)
      } else {
        changeFolder(currentFolders.value.find(i => i.id === entry.id))
      }

    }
  },
  'arrowdown': () => {
    if(selectedFileIndex.value < renderedFileList.value.length - 1) {
      selectedFileIndex.value += 1
    } else {
      selectedFileIndex.value = 0
    }
  },
  'arrowup': () => {
    if(selectedFileIndex.value === 0) {
      selectedFileIndex.value = renderedFileList.value.length - 1
    } else {
      selectedFileIndex.value -= 1
    }
  }
})

const dataStore = useDataStore()
const profileStore = useProfileStore()
const supabase = useSupabaseClient()
const router = useRouter()
const route = useRoute()
const modal = useModal()

dataStore.fetchDocuments()

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

const files = useFiles()

const displayMode = ref("list")
const displayModes = ref([{label: 'Liste',key:'list', icon: 'i-heroicons-list-bullet'},{label: 'Kacheln',key:'rectangles', icon: 'i-heroicons-squares-2x2'}])



const documents = ref([])
const folders = ref([])
const filetags = ref([])

const currentFolder = ref(null)

const loadingDocs = ref(false)
const isDragTarget = ref(false)

const loaded = ref(false)

const setupPage = async () => {
  folders.value = await useSupabaseSelect("folders")

  documents.value = await files.selectDocuments()

  filetags.value = await useSupabaseSelect("filetags")

  if(route.query) {
    if(route.query.folder) {
      currentFolder.value = await useSupabaseSelectSingle("folders", route.query.folder)
    }
  }


  const dropZone = document.getElementById("drop_zone")
  dropZone.ondragover = function (event) {
    modal.open(DocumentUploadModal,{fileData: {folder: currentFolder.value.id, type: currentFolder.value.standardFiletype, typeEnabled: currentFolder.value.standardFiletypeIsOptional}, onUploadFinished: () => {
      setupPage()
      }})
    event.preventDefault()
  }

  dropZone.ondragleave = function (event) {
    isDragTarget.value = false
  }

  dropZone.ondrop = async function (event) {
    console.log("files dropped")
    event.preventDefault()

  }


  loadingDocs.value = false
  loaded.value = true

}
setupPage()
const currentFolders = computed(() => {
  if(folders.value.length > 0) {

    let tempFolders = folders.value.filter(i => currentFolder.value ? i.parent === currentFolder.value.id : !i.parent)

    return tempFolders
  } else return []

})

const breadcrumbLinks = computed(() => {

  if(currentFolder.value) {
    let parents = []

    const addParent = (parent) => {
      parents.push(parent)
      if(parent.parent) {
        addParent(folders.value.find(i => i.id === parent.parent))
      }
    }

    if(currentFolder.value.parent) {
      addParent(folders.value.find(i => i.id === currentFolder.value.parent))
    }

    return [{
      label: "Home",
      click: () => {
        changeFolder(null)
      },
      icon: "i-heroicons-folder"
    },
    ...parents.map(i => {
      return {
        label: folders.value.find(x => x.id === i.id).name,
        click: () => {
          changeFolder(i)
        },
        icon: "i-heroicons-folder"
      }
    }).reverse(),
    {
      label: currentFolder.value.name,
      click: () => {
        changeFolder(currentFolder.value)
      },
      icon: "i-heroicons-folder"
    }]

  } else {
    return [{
      label: "Home",
      click: () => {
        changeFolder(null)
      },
      icon: "i-heroicons-folder"
    }]
  }
})

const filteredDocuments = computed(() => {

  return documents.value.filter(i => currentFolder.value ? i.folder === currentFolder.value.id : !i.folder)

})

const changeFolder = async (newFolder) => {
  loadingDocs.value = true
  currentFolder.value = newFolder

  if(newFolder) {
    fileUploadFormData.value.folder = newFolder.id
    await router.push(`/files?folder=${newFolder.id}`)
  } else {
    fileUploadFormData.value.folder = null
    await router.push(`/files`)
  }

  setupPage()
}

const createFolderData = ref({})
const createFolder = async () => {
  const {data,error} = await supabase
      .from("folders")
      .insert({
        tenant: profileStore.currentTenant,
        parent: currentFolder.value ? currentFolder.value.id : undefined,
        name: createFolderData.value.name,

      })

  createFolderModalOpen.value = false

  setupPage()

}

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

  let files = []

  files = filteredDocuments.value.filter(i => selectedFiles.value[i.id] === true).map(i => i.path)

  // 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") {

      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", "dateien.zip");

  document.body.appendChild(link);

  link.click();
}

const renderedFileList = computed(() => {
    let files = filteredDocuments.value.map(i => {
      return {
        label: i.path.split("/")[i.path.split("/").length -1],
        id: i.id,
        type: "file"
      }
    })

    let folders = currentFolders.value.map(i => {
      return {
        label: i.name,
        id: i.id,
        type: "folder"
      }
    })

    return [...folders,...files]

})
const selectedFileIndex = ref(0)

const showFile = (fileId) => {
  console.log(fileId)
  modal.open(DocumentDisplayModal,{
    documentData: documents.value.find(i => i.id === fileId),
  })
}
const selectedFiles = ref({});

const selectAll = () => {
  if(Object.keys(selectedFiles.value).find(i => selectedFiles.value[i] === true)) {
    selectedFiles.value = {}
  } else {
    selectedFiles.value = Object.fromEntries(filteredDocuments.value.map(i => i.id).map(k => [k,true]))

  }
}



</script>

<template>

  <UDashboardNavbar
      title="Dateien"
  ></UDashboardNavbar>
  <UDashboardToolbar>
    <template #left>
      <UBreadcrumb
          :links="breadcrumbLinks"
      />
    </template>
    <template #right>
      <USelectMenu
        :options="displayModes"
        value-attribute="key"
        option-attribute="label"
        v-model="displayMode"
        :ui-menu="{ width: 'min-w-max'}"
      >
        <template #label>
          <UIcon class="w-5 h-5" :name="displayModes.find(i => i.key === displayMode).icon"/>
        </template>
      </USelectMenu>


      <UButton @click="modal.open(DocumentUploadModal,{fileData: {folder: currentFolder.id, type: currentFolder.standardFiletype, typeEnabled: currentFolder.standardFiletypeIsOptional}, onUploadFinished: () => {setupPage()}})">+ Datei</UButton>
      <UButton
          @click="createFolderModalOpen = true"
          variant="outline"
      >+ Ordner</UButton>
      <UButton
          @click="downloadSelected"
          icon="i-heroicons-cloud-arrow-down"
          variant="outline"
          v-if="Object.keys(selectedFiles).find(i => selectedFiles[i] === true)"
      >Herunterladen</UButton>
      <UModal
          v-model="createFolderModalOpen"
      >
        <UCard>
          <template #header>
            Ordner Erstellen
          </template>



          <UFormGroup
              label="Ordner erstellen"
          >
            <UInput
                v-model="createFolderData.name"
            />
          </UFormGroup>

          <template #footer>
            <UButton
              @click="createFolder"
            >
              Erstellen
            </UButton>
          </template>
        </UCard>

      </UModal>

    </template>
  </UDashboardToolbar>
  <div id="drop_zone" class="h-full scrollList" >
    <div v-if="loaded">
      <UDashboardPanelContent>
        <div v-if="displayMode === 'list'">
          <table class="w-full">
            <thead>
            <tr>
              <td>
                <UCheckbox
                    v-if="renderedFileList.find(i => i.type === 'file')"
                    @change="selectAll"
                />
              </td>
              <td class="font-bold">Name</td>
              <td class="font-bold">Erstellt am</td>
            </tr>
            </thead>
            <tr v-for="(entry,index) in renderedFileList">
              <td>
                <UCheckbox
                    v-if="entry.type === 'file'"
                    v-model="selectedFiles[entry.id]"
                />
              </td>
              <td>
                <UIcon class="mr-1" :name="entry.type === 'folder' ? 'i-heroicons-folder' : 'i-heroicons-document'"/>
                <a
                    style="cursor: pointer"
                    :class="[...index === selectedFileIndex ? ['text-primary', 'text-xl'] : ['dark:text-white','text-black','text-xl']]"
                    @click="entry.type === 'folder' ? changeFolder(currentFolders.find(i => i.id === entry.id)) : showFile(entry.id)"
                >{{entry.label}}</a>

              </td>
              <td>
                <span v-if="entry.type === 'file'" class="text-xl">{{dayjs(documents.find(i => i.id === entry.id).created_at).format("DD.MM.YY HH:mm")}}</span>
                <span v-if="entry.type === 'folder'" class="text-xl">{{dayjs(currentFolders.find(i => i.id === entry.id).created_at).format("DD.MM.YY HH:mm")}}</span>
              </td>
            </tr>
          </table>
        </div>
        <div v-else-if="displayMode === 'rectangles'">
          <div class="flex flex-row w-full flex-wrap" v-if="currentFolders.length > 0">
            <a
                class="w-1/6 folderIcon flex flex-col p-5 m-2"
                v-for="folder in currentFolders"
                @click="changeFolder(folder)"
            >

              <UIcon
                  name="i-heroicons-folder"
                  class="w-20 h-20"
              />
              <span class="text-center truncate">{{folder.name}}</span>
            </a>
          </div>

          <UDivider class="my-5" v-if="currentFolder">{{currentFolder.name}}</UDivider>
          <UDivider class="my-5" v-else>Ablage</UDivider>

          <div v-if="!loadingDocs">
            <DocumentList
                v-if="filteredDocuments.length > 0"
                :documents="filteredDocuments"
                @selectDocument="(info) => console.log(info)"
            />
            <UAlert
                v-else
                class="mt-5 w-1/2 mx-auto"
                icon="i-heroicons-light-bulb"
                title="Keine Dokumente vorhanden"
                color="primary"
                variant="outline"
            />
          </div>
          <UProgress
              animation="carousel"
              v-else
              class="w-2/3 my-5 mx-auto"
          />
        </div>
      </UDashboardPanelContent>
    </div>
    <UProgress animation="carousel" v-else class="w-5/6 mx-auto mt-5"/>

  </div>
</template>

<style scoped>
.folderIcon {
  border: 1px solid lightgrey;
  border-radius: 10px;
  color: dimgrey;
}

.folderIcon:hover {
  border: 1px solid #69c350;
  color: #69c350;
}

tr:nth-child(odd) {
  background-color: rgba(0, 0, 0, 0.05);
}

</style>