<template>
  <main>
    <div>
      <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 ({{ pagination.previous }})</button>
        <span class="mx-3">Page : {{ page }}</span>
        <button @click="goToNextPage">Next page ({{ pagination.next }})</button>
        <span class="mx-2"> (Last page : {{ pagination.last }})</span>
      </div>
      <div class="ma-3">
        <nuxt-link to="/poc/new">Create</nuxt-link>
      </div>
    </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";
  import {Pagination} from "~/types/data";
  import {useReactiveUpdate} from "~/composables/data/useReactiveUpdate";

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

  const totalItems: Ref<number> = ref(0)
  let pagination: Pagination = reactive({first: 1, last: 1, next: undefined, previous: undefined})

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

    // On met à jour les arrays sans les remplacer avec useReactiveUpdate pour ne pas perdre la réactivité
    useReactiveUpdate(files, collection.items)
    useReactiveUpdate(pagination, collection.pagination)
  }
  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>
