<template>
  <main>
    <ul>
      <li v-for="file in files">
        <nuxt-link :to="'/poc/' + file.id" class="mr-3">{{ file.name }}</nuxt-link>
      </li>
    </ul>
    <div class="ma-3">{{ totalItems }} results</div>
    <div class="ma-3">
      <button @click="goToPreviousPage" class="mr-3">Previous page ({{ previousPage }})</button>
      <span class="mx-3">Page : {{ page }}</span>
      <button @click="goToNextPage">Next page ({{ nextPage }})</button>
      <span class="mx-2"> (Last page : {{ lastPage }})</span>
    </div>
    <div class="ma-3">
      <nuxt-link to="/poc/new">Create</nuxt-link>
    </div>
  </main>
</template>

<script setup lang="ts">
  import {useEntityManager} from "~/composables/data/useEntityManager";
  import {Ref} from "@vue/reactivity";
  import ApiResource from "~/models/ApiResource";
  import {File} from "~/models/Core/File";

  const id: Ref<number> = ref(726900)
  const em = useEntityManager()
  let files: Array<ApiResource> = reactive([])
  const page: Ref<number> = ref(1)

  const totalItems: Ref<number> = ref(0)
  const firstPage: Ref<number> = ref(1)
  const lastPage: Ref<number> = ref(1)
  const previousPage: Ref<number | null> = ref(null)
  const nextPage: Ref<number | null> = ref(null)

  const fetchAll = async function() {
    const collection = await em.fetchAll(File, page.value)

    // On met à jour l'array sans la remplacer pour ne pas perdre la réactivité
    em.reactiveUpdate(files, collection.items)

    totalItems.value = collection.totalItems || 0
    firstPage.value = collection.firstPage || 1
    lastPage.value = collection.lastPage || 1
    previousPage.value = collection.previousPage || null
    nextPage.value = collection.nextPage || null
  }
  await fetchAll()

  const goToPreviousPage = async function () {
    if (page.value > 1) {
      page.value--
      await fetchAll()
    }
  }

  const goToNextPage = async function () {
    page.value++
    await fetchAll()
  }

</script>

<style>
a {
  color: blue;
  cursor: pointer;
}
a:hover {
  text-decoration: underline;
}

button {
  border: grey solid 1px;
  padding: 5px;
  margin: 5px;
  cursor: pointer;
}
button:hover {
  text-decoration: underline;
}
button:focus {
  background-color: lightgrey;
}
</style>
