<script setup>


import {BlobReader, BlobWriter, ZipWriter} from "@zip.js/zip.js";
import DocumentDisplayModal from "~/components/DocumentDisplayModal.vue";
import DocumentUploadModal from "~/components/DocumentUploadModal.vue";
import dayjs from "dayjs";
import arraySort from "array-sort";



defineShortcuts({
  '+': () => {
    //Hochladen
    uploadModalOpen.value = true
  },
  'Enter': {
    usingInput: true,
    handler: () => {
      let entry = renderedFileList.value[selectedFileIndex.value]

      if(entry.type === "file") {
        showFile(entry.id)
      } else if(createFolderModalOpen.value === false && entry.type === "folder") {
        changeFolder(currentFolders.value.find(i => i.id === entry.id))
      } else if(createFolderModalOpen.value === true) {
        createFolder()
      }

    }
  },
  '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 tempStore = useTempStore()
const router = useRouter()
const route = useRoute()
const modal = useModal()

const auth = useAuthStore()

const uploadModalOpen = ref(false)
const createFolderModalOpen = ref(false)
const uploadInProgress = ref(false)
const fileUploadFormData = ref({
  tags: ["Eingang"],
  path: "",
  tenant: auth.activeTenant,
  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 useEntities("folders").select()

  documents.value = await files.selectDocuments()

  filetags.value = await useEntities("filetags").select()

  if(route.query) {
    if(route.query.folder) {
      currentFolder.value = await useEntities("folders").selectSingle(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) {
    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 res = await useEntities("folders").create({
    parent: currentFolder.value ? currentFolder.value.id : undefined,
    name: createFolderData.value.name,
  })

  createFolderModalOpen.value = false

  setupPage()

}

const downloadSelected = async () => {

  let files = []

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


  await useFiles().downloadFile(undefined,Object.keys(selectedFiles.value))

}

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

    arraySort(files, (a,b) => {
      let aVal = a.path ? a.path.split("/")[a.path.split("/").length -1] : null
      let bVal = b.path ? b.path.split("/")[b.path.split("/").length -1] : null

      if(aVal && bVal) {
        return aVal.localeCompare(bVal)
      } else if(!aVal && bVal) {
        return 1
      } else {
        return -1
      }
    }, {reverse: true})

    if(searchString.value.length > 0) {
      files = useSearch(searchString.value, files)
    }


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

    arraySort(folders, "label")

    /*folders.sort(function(a, b) {

      // Compare the 2 dates
      if (a.name < b.name) return -1;
      if (a.name > b.name) return 1;
      return 0;
    });*/
    return [...folders,...files]

})
const selectedFileIndex = ref(0)

const showFile = (fileId) => {
  modal.open(DocumentDisplayModal,{
    documentData: documents.value.find(i => i.id === fileId),
    onUpdatedNeeded: setupPage()
  })
}
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]))

  }
}

const clearSearchString = () => {
  tempStore.clearSearchString("files")
  searchString.value = ''
}



</script>

<template>

  <UDashboardNavbar
      title="Dateien"
  >
    <template #right>
      <UInput
          id="searchinput"
          v-model="searchString"
          icon="i-heroicons-funnel"
          autocomplete="off"
          placeholder="Suche..."
          class="hidden lg:block"
          @keydown.esc="$event.target.blur()"
          @change="tempStore.modifySearchString('files',searchString)"
      >
        <template #trailing>
          <UKbd value="/" />
        </template>
      </UInput>
      <UButton
          icon="i-heroicons-x-mark"
          variant="outline"
          color="rose"
          @click="clearSearchString()"
          v-if="searchString.length > 0"
      />
    </template>
  </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
          :disabled="!currentFolder"
          @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>