<template>
  <div>
    <template v-if="!forLogging">

      <div class="columns">
        <div class="column">
          <app-text-field label="Name" v-model="recipe.name"></app-text-field>
        </div>

        <div class="column">
          <app-text-field label="Source" v-model="recipe.source"></app-text-field>
        </div>
      </div>

      <app-text-field label="Description" type="textarea" v-model="recipe.description"></app-text-field>

      <div class="field">
        <label class="label is-small-mobile">Tags</label>
        <app-tag-editor v-model="recipe.tags"></app-tag-editor>
      </div>

    </template>

    <div class="columns">
      <div class="column">
        <app-text-field label="Yields" v-model="recipe.yields"></app-text-field>
      </div>

      <div class="column">
        <app-text-field label="Total Time" type="number" v-model="recipe.total_time"></app-text-field>
      </div>

      <div class="column">
        <app-text-field label="Active Time" v-model="recipe.active_time"></app-text-field>
      </div>
    </div>

    <h3 class="title is-4">Ingredients</h3>

    <recipe-edit-ingredient-editor :ingredients="recipe.ingredients"></recipe-edit-ingredient-editor>


    <div class="field">
      <label class="label title is-4">Directions</label>
      <div class="control columns">
        <div class="column">
          <textarea ref="step_text_area" class="textarea directions-input" v-model="recipe.step_text"></textarea>
        </div>
        <div class="column">
          <div class="box content" v-html="stepPreview">
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>

  import autosize from "autosize";
  import debounce from "lodash/debounce";
  import api from "../lib/Api";

  import RecipeEditIngredientEditor from "./RecipeEditIngredientEditor";

  export default {
    props: {
      recipe: {
        required: true,
        type: Object
      },
      forLogging: {
        required: false,
        type: Boolean,
        default: false
      }
    },

    data() {
      return {
        stepPreviewCache: null
      };
    },

    computed: {
      stepPreview() {
        if (this.stepPreviewCache === null) {
          return this.recipe.rendered_steps;
        } else {
          return this.stepPreviewCache;
        }
      }
    },

    methods: {

      updatePreview: debounce(function() {
        api.postPreviewSteps(this.recipe.step_text)
          .then(data => this.stepPreviewCache = data.rendered_steps)
          .catch(err => this.stepPreviewCache = "?? Error ??");
      }, 750)
    },

    watch: {
      'recipe.step_text': function() {
        this.updatePreview();
      }
    },

    mounted() {
      //autosize(this.$refs.step_text_area);
    },

    components: {
      RecipeEditIngredientEditor
    }
  }

</script>

<style lang="scss" scoped>
  .bulk-input {
    height: 100%;
  }

  .directions-input {
    height: 100%;
  }
</style>