<template>
  <div>
    <div class="row g-3 align-items-center" v-if="!manualMode">
      <div class="col-auto">
        <input name="searchTerm" class="input form-control" placeholder="book title to search" @keypress.enter="search"
               v-model="searchTerm" type="text"/>

      </div>
      <div class="col-auto">
        <button class="btn btn-info" @click="search">Szukaj</button>
      </div>
    </div>
    <div class="row mt-4" v-if="!manualMode">
      <div class="col-auto">
        <a class="link-primary cursor-pointer" @click="manualMode=true">Let me fill in data manually</a>
      </div>
    </div>
    <div v-if="selectedBook && selectedBook.cover_url.small">
      <img :src="selectedBook.cover_url.small" class="img-thumbnail"/>
    </div>
    <div v-if="books.length" v-for="book in books">
      <div class="d-flex flex-row border mb-3 cursor-pointer book-search-item" @click="getBookDetails(book.url)">
        <img :src="book.cover_url.small" class="img-fluid rounded-start">
        <div class="card-body">
          <h5 class="card-title">{{ book.title }} ({{ book.author }})</h5>
          <p class="card-text"><a :href="book.url"><small class="text-muted">{{ book.url }}</small></a></p>
        </div>
      </div>
    </div>
    <h1 v-else>Oh no 😢</h1>

    <div v-show="manualMode">
      <slot></slot>
      <BookForm></BookForm>
    </div>
  </div>
</template>

<script>
import BookForm from '../components/bookform'
import axios from 'axios';

export default {
  name: 'Book',
  components: {BookForm},
  data() {
    return {
      searchTerm: null,
      books: [],
      selectedBook: null,
      manualMode: false
    }
  },
  methods: {
    search: function () {
      axios.get('/book/search/' + this.searchTerm).then(response => {
        this.books = response.data;
      });
    },
    getBookDetails: function (url) {
      this.manualMode = true;
      axios.get('/book/info/' + btoa(url)).then(response => {
        const book = this.selectedBook = response.data;
        this.$el.querySelector('#book_title').value = book.title;
        this.$el.querySelector('#book_author').value = book.author;
        this.$el.querySelector('#book_isbn').value = book.isbn;
        this.$el.querySelector('#book_pages').value = book.pages;
        this.$el.querySelector('#book_publish_date').value = book.datePublished;
        this.$el.querySelector('#book_publisher').value = book.publisher;
        this.$el.querySelector('#book_category').value = book.category;
        this.$el.querySelector('#book_language').value = book.language;
        this.$el.querySelector('#book_description').value = book.description;
        this.$el.querySelector('#book_series').value = book.cycle || '';
        this.$el.querySelector('#book_volume').value = book.volume || '';
        this.$el.querySelector('#book_cover_url').value = book.cover_url.large || '';
        this.books = [];
        this.searchTerm = '';
      });
    }
  },
  mounted() {

  }
}
</script>