<template>
  <div>
    <input type="text" class="form-control" v-model="searchTerm" @keydown.enter="search"/>
    <table class="table">
      <thead>
      <tr>
        <th></th>
        <th>Title</th>
        <th>Description</th>
        <th>Rating</th>
        <th>Publisher</th>
        <th>Publish date</th>
        <th>Actions</th>
      </tr>
      </thead>
      <tbody>
      <tr v-if="books.length" v-for="book in books">
        <td>
          <a :href="'/book/'+book.id">
            <img class="img-thumbnail" style="max-width: 80px" :src="'/book_covers/cover_'+book.id+'.jpg'"/>
          </a>
        </td>
        <td><a :href="'/book/'+book.id" class="text-decoration-none">{{ book.title }}</a></td>
        <td>{{ book.short_description }}</td>
        <td>{{ '⭐'.repeat(book.rating) }}</td>
        <td>{{ book.publisher }}</td>
        <td>{{ book.publish_date }}</td>
        <td>
          <a :href="'/book/'+book.id" class="text-decoration-none">show</a>
          <a :href="'/book/'+book.id+'/edit/'" class="text-decoration-none">edit</a>
        </td>
      </tr>
      <tr v-else>
        <td colspan="9">no records found</td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import {mapActions, mapState} from "vuex";

export default {
  name: 'BookListing',
  data() {
    return {
      searchTerm: null,
      selectedBook: null,
      manualMode: false
    }
  },
  computed: {
    ...mapState('booksmodule', ['books']),
  },
  methods: {
    ...mapActions('booksmodule', [
      'findAll'
    ]),
    search: function () {
      this.$store.commit('increment')
      this.updateHistory();
      this.findAll(this.searchTerm);
    },
    updateHistory: function () {
      if (history.pushState) {
        let url = window.location.protocol + "//" + window.location.host + window.location.pathname + '?search=' + this.searchTerm;
        window.history.pushState({path: url}, '', url);
      }
    }
  },
  mounted() {
    const urlParams = new URLSearchParams(window.location.search);
    this.searchTerm = urlParams.get('search') || "";
    this.search();
  }
}
</script>