<script setup>
import { ref, computed } from 'vue'
import { getAllBooks } from './api.js'
import { onBeforeRouteUpdate } from 'vue-router'
import BookListElement from './BookListElement.vue'
import Pagination from './Pagination.vue'

const limit = 5
const pageNumber = ref(1)

const offset = computed(() => (pageNumber.value - 1) * limit)

const data = ref(null)
const error = ref(null)

const pageTotal = computed(() => {
  const countValue = data.value !== null ? data.value['count'] : 0
  return Math.ceil(countValue / limit)
})

function fetchData() {
  data.value = null
  error.value = null
  getAllBooks(data, error, limit, offset.value)
}

fetchData()

onBeforeRouteUpdate(async (to, from) => {
  pageNumber.value = 1
  fetchData()
})

function pageChange(newPageNumber) {
  pageNumber.value = newPageNumber
  fetchData()
}
</script>

<template>
  <div>
    <div>
      <div v-if="error">{{ error }}</div>
      <div v-else-if="data && data.books && data.books.length > 0">
        <div class="booksearchlist" v-for="book in data.books" :key="book.id">
          <BookListElement v-bind="book" />
        </div>
      </div>
      <div v-else-if="data === null">{{ $t('searchbook.loading') }}</div>
      <div v-else>{{ $t('searchbook.noresult') }}</div>
    </div>
    <Pagination
      :pageNumber="pageNumber"
      :pageTotal="pageTotal"
      maxItemDisplayed="11"
      @pageChange="pageChange"
    />
  </div>
</template>

<style scoped></style>
