<template>
  <div>
    <h1 class="title">Ingredients</h1>

    <router-link :to="{name: 'new_ingredient'}" class="button is-primary">Create Ingredient</router-link>

    <table class="table">
      <thead>
      <tr>
        <th>Name</th>
        <th>USDA</th>
        <th>KCal per 100g</th>
        <th>Density</th>
        <th></th>
      </tr>
      <tr>
        <th>
          <div class="field">
            <div class="control">
              <input type="text" class="input" placeholder="search names" v-model="search.name">
            </div>
          </div>
        </th>
        <th colspan="4"></th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="i in ingredients" :key="i.id">
        <td><router-link :to="{name: 'ingredient', params: { id: i.id } }">{{i.name}}</router-link></td>
        <td><app-icon v-if="i.usda" icon="check"></app-icon></td>
        <td>{{i.kcal}}</td>
        <td>{{i.density}}</td>
        <td>
          <button type="button" class="button is-danger">X</button>
        </td>
      </tr>
      </tbody>
    </table>

  </div>
</template>

<script>

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

  export default {
    data() {
      return {
        ingredientData: null,
        search: {
          page: 1,
          per: 25,
          name: null
        }
      };
    },

    computed: {
      ingredients() {
        if (this.ingredientData) {
          return this.ingredientData.ingredients;
        } else {
          return [];
        }
      }
    },

    methods: {

      getList: debounce(function() {
        this.loadResource(
          api.getIngredientList(this.search.page, this.search.per, this.search.name)
            .then(data => this.ingredientData = data)
        );
      }, 500, {leading: true, trailing: true})
    },

    created() {
      this.$watch("search",
        () => this.getList(),
        {
          deep: true,
          immediate: true
        }
      );
    },

    components: {
      AppIcon
    }
  }

</script>