<template>
  <main>
    <div>
      <div v-if="pending">
        Pending...
      </div>
      <div v-else>
        <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>
          <p><nuxt-link to="/poc/1">Goto 1</nuxt-link></p>
        </div>
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
  import {useEntityManager} from "~/composables/data/useEntityManager";
  import {computed, ComputedRef, ref, Ref} from "@vue/reactivity";
  import ApiResource from "~/models/ApiResource";
  import {File} from "~/models/Core/File";
  import {Collection, Pagination} from "~/types/enum/data";
  import {useLazyAsyncData} from "#app";
  import {useEntityFetch} from "~/composables/data/useEntityFetch";

  const { em } = useEntityManager()

  const page: Ref<number> = ref(1)

  let { data: collection, pending, refresh } = useLazyAsyncData(
      'files',
      () => em.fetchCollection(File, null, { page: page.value })
  )
  console.log(collection.value)

  const totalItems: ComputedRef<number | undefined> = computed(() => collection.value?.totalItems)

  const pagination: ComputedRef<Pagination | undefined> = computed(() => {
    return collection.value?.pagination
  })

  let files: ComputedRef<Array<ApiResource> | undefined> = computed(() => {
    return collection.value?.items
  })

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

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

</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>
