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

    <div class="ui positive message" v-if="success">
      <div class="header">
        Success
      </div>
      {{ success }}
    </div>

    <form class="ui form" v-bind:class="{ loading: loading }" v-if="!success" @submit.prevent="insertOrUpdatePublisher">
      <div class="field">
        <label>Name</label>
        <input name="Name" placeholder="Name" type="text" v-model="publisher.Name" required>
      </div>
      <button class="ui blue button" type="submit">Submit</button>
    </form>
  </div>
</template>

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

  export default {
    name: 'PublishersAddEdit',
    data () {
      return {
        error: '',
        success: '',
        loading: false,
        publisherID: this.$route.params.id,
        edit: false,
        publisher: {
          Name: ''
        }
      }
    },
    created () {
      this.loading = true

      // Look if we're in edit mode and get the publisher infos if nessesary
      if (this.publisherID) {
        HTTP.get('publishers/' + this.publisherID)
          .then(response => {
            this.publisher = response.data
            this.edit = true
          })
          .catch(e => {
            this.error = e
          })
      }
      this.loading = false
    },
    methods: {
      insertOrUpdatePublisher: function () {
        if (this.publisher.Lastname === '') {
          this.error = {message: 'Please provide name.'}
        } else {
          this.loading = true

          // Finally Send it
          // If we want to newly insert it, make a different request
          if (this.edit) {
            HTTP.post('publishers/' + this.publisher.ID, {publisher: this.publisher})
              .then(response => {
                this.loading = false
                this.success = 'The publisher was successfully updated!'
                this.error = ''
              })
              .catch(e => {
                this.loading = false
                this.error = e
              })
          } else { // insert a new publisher
            HTTP.put('publishers', {publisher: this.publisher})
              .then(response => {
                this.loading = false
                this.success = 'The publisher was successfully inserted!'
                this.error = ''
              })
              .catch(e => {
                this.loading = false
                this.error = e
              })
          }
        }
      }
    }
  }
</script>
