<template>
  <div>

    <div v-if="ingredient === null">
      Loading...
    </div>
    <div v-else>
      <ingredient-edit :ingredient="ingredient"></ingredient-edit>
    </div>

    <button type="button" class="button is-primary" @click="save">Save</button>
    <router-link class="button is-secondary" to="/ingredients">Cancel</router-link>

  </div>
</template>

<script>

  import IngredientEdit from "./IngredientEdit";
  import { mapState } from "vuex";
  import api from "../lib/Api";
  import * as Errors from '../lib/Errors';

  export default {
    data: function () {
      return {
        ingredient: null,
        validationErrors: null
      };
    },

    computed: {
      ...mapState({
        ingredientId: state => state.route.params.id,
      })
    },

    methods: {
      save() {
        this.loadResource(
          api.patchIngredient(this.ingredient)
            .then(() => this.$router.push({name: 'ingredient', params: {id: this.ingredientId }}))
            .catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
        );
      }
    },

    created() {
      this.loadResource(
        api.getIngredient(this.ingredientId)
          .then(data => { this.ingredient = data; return data; })
      );
    },

    components: {
      IngredientEdit
    }
  }

</script>

<style lang="scss" scoped>
</style>