<template>
  <div v-if="user.authenticated">
    <h1>{{ booksTitle }}</h1>

    <div class="ui info message" v-if="loading">
      <icon name="refresh" spin></icon>&nbsp;&nbsp;
      Loading...
    </div>

    <div class="ui negative message" v-if="error">
      <div class="header">
        An erro occured.
      </div>
      {{ error.message }}
      <div v-if="error.response">
      {{ error.response.Message }}
      </div>
    </div>

    <div v-if="!loading">
      <form id="search">
        <div class="ui icon input">
          <input placeholder="Search for anything..." type="text" v-model="searchQuery">
          <i class="search icon"></i>
        </div>
      </form>
      <paginate
        name="books"
        :list="filteredData"
        :per="25"
        tag="div"
      >
        <grid
          :data="paginated('books')"
          :columns="gridColumns"
        >
        </grid>
      </paginate>
      <div class="pagination-container">
        <paginate-links
          tag="div"
          for="books"
          :hide-single-page="true"
          :classes="{
            'ul': ['ui', 'pagination', 'menu'],
            'li': 'item',
            'li a': 'pagination-link'
          }"
        >
        </paginate-links>
        <div v-if="$refs.paginator">
          Viewing {{$refs.paginator.pageItemsCount}} results
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import auth from '../auth'
import {HTTP} from '../http-common'

export default {
  name: 'Home',
  data () {
    return {
      user: auth.user,
      booksTitle: 'Books Overview',
      books: [],
      searchQuery: '',
      gridColumns: ['Title', 'ISBN', 'Year', 'Price', 'Author', 'Publisher', 'Status'],
      loading: false,
      paginate: ['books'],
      error: ''
    }
  },
  created () {
    this.loadBooks()
  },
  watch: {
    // call again the method if the route changes
    '$route': 'loadBooks'
  },
  computed: {
    filteredData: function () {
      var filterKey = this.searchQuery && this.searchQuery.toLowerCase()
      var data = this.books
      if (filterKey) {
        data = data.filter(function (row) {
          return Object.keys(row).some(function (key) {
            return String(row[key]).toLowerCase().indexOf(filterKey) > -1
          })
        })
      }
      return data
    }
  },
  methods: {
    loadBooks () {
      this.loading = true
      HTTP.get(`books`)
        .then(response => {
          let bs = response.data
          let i = 0

          // Loop throught the data we got from our API and prepare an array to display all books
          for (const b in bs) {
            this.books[i] = {
              Title: bs[b].Title,
              ISBN: bs[b].Isbn,
              Year: bs[b].Year,
              Price: bs[b].Price + '€',
              Author: '',
              Publisher: bs[b].PublisherFull.Name,
              Status: bs[b].Status
            }

            // Get all authors and concat them into one singe string
            let authors = bs[b].Authors
            for (const au in authors) {
              this.books[i].Author += authors[au].Forename + ' ' + authors[au].Lastname
              if (authors.length > au + 1) {
                this.books[i].Author += ', '
              }
            }
            i++
          }
          this.loading = false
        })
        .catch(e => {
          console.log(e)
          this.error = e
        })
    }
  }
}
</script>

<style>
  a.pagination-link{
    margin: -5px -1.14286em -18px;
    display: block;
    position: absolute;
    cursor: pointer;
    padding: 0.928571em 1.14286em;
    color: rgba(0,0,0,.87);

    -webkit-transition: background-color 200ms; /* Safari */
    transition: background-color 200ms;
  }

  a.pagination-link:hover{
    background: rgba(0,0,0,.02);
  }

  .pagination{
    padding: 0;
  }

  .pagination-container{
    margin-top: 1rem;
    text-align: center;
  }

  #search{
    margin-bottom: 1rem;
  }
</style>
