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

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

    <div v-if="!loading">

      <router-link :to="{ name: 'book-edit', params: { id: bookID} }" class="ui teal labeled icon button" style="float: right;">
        <i class="edit icon"></i>
        <span v-lang.general.edit></span>
      </router-link>

      <list :infos="bookList" />

      <p class="grey">
        <span v-lang.general.created="this.createdTime"></span><br/>
        <span v-if="this.book.created !== this.book.updated" v-lang.general.lastEdit="this.editedTime"></span>
      </p>
    </div>
  </div>
</template>

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

  export default {
    name: 'Book',
    data () {
      return {
        user: auth.user,
        book: {},
        allStatus: [],
        bookID: this.$route.params.id,
        bookList: {},
        AuthorList: [],
        createdTime: {
          date: '',
          time: ''
        },
        editedTime: {
          date: '',
          time: ''
        }
      }
    },
    created () {
      this.loadStatus()
      this.loadBook()

      document.title = this.translate('nav').books
    },
    watch: {
      // call again the method if the route changes
      '$route': 'loadBook'
    },
    methods: {
      errorNotification (e) {
        // Build the notification text from error response
        let err = e.message
        if (e.response.data.message) {
          err += '<br/>' + e.response.data.message
        }

        // Fire a notification
        this.$notify({
          type: 'error',
          title: this.langGeneral.error,
          text: err
        })
      },
      loadBook () {
        this.loading = true
        this.book = {}
        HTTP.get(`books/` + this.bookID)
          .then(response => {
            this.book = response.data

            // Get all authors and build an array with them
            let authors = this.book.authors
            for (const au in authors) {
              this.AuthorList.push({
                content: authors[au].forename + ' ' + authors[au].lastname,
                link: {
                  name: 'author-show',
                  params: {
                    id: authors[au].id
                  }
                }
              })
            }

            // Make Status a name, not an id
            this.book.status = this.getStatusByID(this.book.status)

            // Build the list object
            this.bookList = [
              {
                header: this.translate('books').description,
                content: this.book.description.replace(/\n/g, '<br>')
              },
              {
                header: this.translate('books').gridColumns.isbn,
                content: this.book.isbn
              },
              {
                header: this.translate('books').gridColumns.year,
                content: this.book.year
              },
              {
                header: this.translate('books').gridColumns.price,
                content: this.book.price
              },
              {
                header: this.translate('books').gridColumns.quantity,
                content: this.book.quantity
              },
              {
                header: this.translate('books').gridColumns.status,
                content: this.book.status
              },
              {
                header: this.translate('books').gridColumns.publisher,
                content: this.book.publisher.name,
                link: {
                  name: 'publisher-show',
                  params: {
                    id: this.book.publisher.id
                  }
                }
              },
              {
                header: this.translate('books').gridColumns.authors,
                content: this.AuthorList
              }
            ]

            // Beautify the date
            let c = new Date(this.book.created * 1000)
            // c.setSeconds()
            this.createdTime = {
              date: ('0' + c.getDate()).slice(-2) + '.' + ('0' + (c.getMonth() + 1)).slice(-2) + '.' + c.getFullYear(),
              time: ('0' + c.getHours()).slice(-2) + ':' + ('0' + c.getMinutes()).slice(-2)
            }

            let e = new Date(this.book.updated * 1000)
            // e.setSeconds()
            this.editedTime = {
              date: ('0' + e.getDate()).slice(-2) + '.' + ('0' + (e.getMonth() + 1)).slice(-2) + '.' + e.getFullYear(),
              time: ('0' + e.getHours()).slice(-2) + ':' + ('0' + e.getMinutes()).slice(-2)
            }

            // Set the title
            document.title = this.book.title + ' | ' + this.translate('nav').books

            this.loading = false
          })
          .catch(e => {
            this.loading = false
            this.errorNotification(e)
          })
      },
      loadStatus: function () {
        HTTP.get('status')
          .then(response => {
            this.allStatus = response.data
          })
          .catch(e => {
            this.errorNotification(e)
          })
      },
      getStatusByID: function (id) {
        // TODO: is there a better way to do this?
        for (const i in this.allStatus) {
          if (this.allStatus[i].ID === id) {
            return this.allStatus[i].Name
          }
        }
        return ''
      }
    }
  }
</script>
