<template>
  <div>

    <ingredient-edit :ingredient="ingredient" action="Creating"></ingredient-edit>

    <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() {
      return {
        ingredient: {
          name: null,
          notes: null,
          ndbn: null,
          density: null,
          water: null,
          ash: null,
          protein: null,
          kcal: null,
          fiber: null,
          sugar: null,
          carbohydrates: null,
          calcium: null,
          iron: null,
          magnesium: null,
          phosphorus: null,
          potassium: null,
          sodium: null,
          zinc: null,
          copper: null,
          manganese: null,
          vit_c: null,
          vit_b6: null,
          vit_b12: null,
          vit_a: null,
          vit_e: null,
          vit_d: null,
          vit_k: null,
          cholesterol: null,
          lipids: null,
          ingredient_units: []
        },
        validationErrors: null
      }
    },

    methods: {
      save() {
        this.loadResource(
          api.postIngredient(this.ingredient)
            .then(() => this.$router.push('/ingredients'))
            .catch(Errors.onlyFor(Errors.ApiValidationError, err => this.validationErrors = err.validationErrors()))
        );
      }
    },

    components: {
      IngredientEdit
    }
  }

</script>

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