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

  const limit = 5;
  const pageNumber = ref(1);

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

  const props = defineProps({
    searchterm: String
  });

  let data = ref(null);
  let error = ref(null);
  let totalBooksData = ref(null);
  let errorFetchTotal = ref(null);

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

  fetchData(props.searchterm);


  function fetchData(searchTerm) {
    getSearchBooks(data, error, searchTerm, limit, offset.value);
    getCountSearchBooks(totalBooksData, errorFetchTotal, searchTerm);
  }

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

  function pageChange(newPageNumber) {
    pageNumber.value = newPageNumber;
    data.value = null;
    fetchData(props.searchterm);
  }

</script>

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

<style scoped></style>

