<template>
  <div v-if="user.authenticated">
    <h1>{{ author.forename }} {{ author.lastname }}</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: 'author-edit', params: { id: authorID} }" class="ui teal labeled icon button" style="float: right;">
        <i class="edit icon"></i>
        <span v-lang.general.edit></span>
      </router-link>

      <list :infos="authorList"/>
    </div>
  </div>
</template>

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

  export default {
    name: 'Author',
    data () {
      return {
        user: auth.user,
        author: {},
        authorID: this.$route.params.id,
        authorList: []
      }
    },
    created () {
      this.loadAuthor()
    },
    watch: {
      // call again the method if the route changes
      '$route': 'loadAuthor'
    },
    methods: {
      loadAuthor () {
        this.loading = true
        this.author = {}
        HTTP.get(`authors/` + this.authorID)
          .then(response => {
            this.author = response.data

            // Make a list
            this.authorList = [
              {
                header: this.translate('authors').forename,
                content: this.author.forename
              },
              {
                header: this.translate('authors').lastname,
                content: this.author.lastname
              }
            ]

            this.loading = false
          })
          .catch(e => {
            this.loading = false
            // 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
            })
          })
      }
    }
  }
</script>
