<template>
  <div class="row">
    <div class="input-field col s4">
      <input
        :id="identifier + '_name'"
        v-model="variant.name"
        placeholder="Variantenbezeichnung"
        type="text"
        class="validate"
      >
      <label
        :for="identifier + '_name'"
        class="active"
      >Variantenbezeichnung</label>
    </div>
    <div class="input-field col s4">
      <input
        :id="identifier + '_price'"
        v-model.number="variant.price"
        placeholder="Preis"
        type="number"
        class="validate"
        step="0.01"
      >
      <label
        :for="identifier + '_price'"
        class="active"
      >Preis</label>
    </div>
    <div class="input-field col s2">
      <input
        :value="article.PortionPrice + variant.Price"
        class="validate"
        disabled
      >
    </div>
    <div class="input-field col s2">
      <a
        href="#"
        @click="storeVariant(variant)"
      >Variante speichern</a>
    </div>
  </div>
</template>

<script>
import { Article } from '../model/article';
import { thawVariant, Variant } from '../model/variant'
export default {
  name: 'Variant',
  props: {
    variant: {
      type: Object,
      default() { return new Variant(); }
    },
    article: {
      type: Object,
      default() { return new Article(); }
    },
    identifier: {
      type: String
    }
  },
  methods: {
    storeVariant: function(variant) {
      variant.ArticleId = this.article.id;
      this.$http
        .post(
          "/api/varianten" + (variant.id > 0 ? '/' + variant.id : ''),
          JSON.stringify(variant),
          {
            headers: {
              'Content-Type': 'application/json'
            }
          }
        )
        .then(response => {
          this.$M.toast({ html: response.data + " Variante aktualisiert." });
          this.variant = thawVariant(response.data);
        })
        .catch(error => {
          this.$M.toast({ html: error });
        });
    },
    deleteVariant: function(variant) {
      this.$http
        .delete(
          "/api/varianten/" + variant.id,
        )
        .then(response => {
          this.$emit('delete-variant', variant);
          this.$M.toast({ html: response.data + " Varianten gelöscht." });
        })
        .catch(error => {
          this.$M.toast({ html: response });
        });
    },
  }
}
</script>
