<template>
  <div>
    <div class="ui positive message" v-if="success">
      <div class="header" v-lang.general.success></div>
      {{ success }}
    </div>

    <form class="ui form" v-bind:class="{ loading: loading }" v-if="!success" @submit.prevent="insertOrUpdateItem">
      <div class="field">
        <label v-lang.items.gridColumns.title></label>
        <input name="title" :placeholder="langItems.gridColumns.title" type="text" v-model="item.title" v-focus required>
      </div>

      <div class="field">
        <label v-lang.items.description></label>
        <textarea name="description" :placeholder="langItems.description" rows="3" v-model="item.description"></textarea>
      </div>

      <div class="two fields">
        <div class="field">
          <label v-lang.items.gridColumns.price></label>
          <input name="price" :placeholder="langItems.gridColumns.price" type="number" v-model.number="item.price" step="0.01" min="0">
        </div>

        <div class="field">
          <label v-lang.items.gridColumns.quantity></label>
          <input name="quantity" :placeholder="langItems.gridColumns.quantity" type="number" v-model.number="item.quantity" step="1">
        </div>
      </div>

      <button class="ui blue button" type="submit" v-lang.general.submit></button>
    </form>
  </div>
</template>

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

  export default {
    name: 'ItemsAddEdit',
    data () {
      return {
        success: '',
        loading: false,
        itemID: this.$route.params.id,
        edit: false,
        item: {
          title: '',
          price: 0,
          description: '',
          quantity: 0
        }
      }
    },
    created () {
      this.loading = true

      // Look if we're in edit mode and get the item infos if nessesary
      if (this.itemID) {
        HTTP.get('items/' + this.itemID)
          .then(response => {
            this.item = response.data
            this.edit = true
          })
          .catch(e => {
            this.errorNotification(e)
          })
      }

      // Set the title
      document.title = this.translate('items').newItem + ' | ' + this.translate('nav').items
      if (this.itemID) {
        document.title = this.translate('general').edit + ' | ' + this.translate('nav').items
      }

      this.loading = false
    },
    computed: {
      langItems () {
        return this.translate('items')
      }
    },
    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.translate('general').error,
          text: err
        })
      },
      insertOrUpdateItem: function () {
        if (this.item.Lastname === '') {
          // Fire a notification
          this.$notify({
            type: 'warn',
            text: this.translate('items').errorNoTitle
          })
        } else {
          this.loading = true

          // Finally Send it
          // If we want to newly insert it, make a different request
          if (this.edit) {
            HTTP.post('items/' + this.item.id, this.item, { headers: {'Authorization': 'Bearer ' + localStorage.getItem('token')} })
              .then(response => {
                this.loading = false

                // Fire a notification
                this.$notify({
                  type: 'success',
                  title: this.translate('general').success,
                  text: this.translate('items').updatedSuccess
                })

                // Redirect to items list
                router.push({ name: 'items' })
              })
              .catch(e => {
                this.loading = false
                this.errorNotification(e)
              })
          } else { // insert a new item
            HTTP.put('items', this.item, { headers: {'Authorization': 'Bearer ' + localStorage.getItem('token')} })
              .then(response => {
                this.loading = false

                // Fire a notification
                this.$notify({
                  type: 'success',
                  title: this.translate('general').success,
                  text: this.translate('items').insertedSuccess
                })

                // Redirect to items list
                router.push({ name: 'items' })
              })
              .catch(e => {
                this.loading = false
                this.errorNotification(e)
              })
          }
        }
      }
    }
  }
</script>
