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

    <router-link v-if="isLoggedIn" :to="{name: 'new_recipe'}" class="button is-primary">Create Recipe</router-link>

    <app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="recipe" @changePage="changePage"></app-pager>

    <table class="table">
      <thead>
        <tr>
          <th v-for="h in tableHeader" :key="h.name">
            <a v-if="h.sort" href="#" @click.prevent="setSort(h.name)">
              {{h.label}}
              <app-icon v-if="search.sortColumn === h.name" size="sm" :icon="search.sortDirection === 'asc' ? 'caret-bottom' : 'caret-top'"></app-icon>
            </a>
            <span v-else>{{h.label}}</span>
          </th>
          <th></th>
        </tr>
        <tr>
          <td>
            <div class="field">
              <div class="control">
                <input type="text" class="input" placeholder="search names" v-model="search.name">
              </div>
            </div>
          </td>
          <td>
            <div class="field">
              <div class="control">
                <input type="text" class="input" placeholder="search tags" v-model="search.tags">
              </div>
            </div>
          </td>
          <td colspan="5"></td>
        </tr>
      </thead>
      <tbody>
        <tr v-for="r in recipes" :key="r.id">
          <td><router-link :to="{name: 'recipe', params: { id: r.id } }">{{r.name}}</router-link></td>
          <td>
            <div class="tags">
              <span class="tag" v-for="tag in r.tags" :key="tag">{{tag}}</span>
            </div>
          </td>
          <td>
            <app-rating v-if="r.rating !== null" :value="r.rating" readonly></app-rating>
            <span v-else>--</span>
          </td>
          <td>{{ r.yields }}</td>
          <td>{{ formatRecipeTime(r.total_time, r.active_time) }}</td>
          <td><app-date-time :date-time="r.created_at" :show-time="false"></app-date-time></td>
          <td>
            <router-link v-if="isLoggedIn" :to="{name: 'new_log', params: { recipeId: r.id } }" class="button is-primary">
              <app-icon icon="star" size="md"></app-icon>
            </router-link>
            <router-link v-if="isLoggedIn" :to="{name: 'edit_recipe', params: { id: r.id } }" class="button is-primary">
              <app-icon icon="pencil" size="md"></app-icon>
            </router-link>
            <button v-if="isLoggedIn" type="button" class="button is-danger">
              <app-icon icon="x" size="md"></app-icon>
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <app-pager :current-page="currentPage" :total-pages="totalPages" paged-item-name="recipe" @changePage="changePage"></app-pager>

  </div>
</template>

<script>

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

  export default {
    data() {
      return {
        recipeData: null,
        search: {
          sortColumn: 'created_at',
          sortDirection: 'desc',
          page: 1,
          per: 25,
          name: null,
          tags: null
        }
      };
    },

    computed: {
      recipes() {
        if (this.recipeData) {
          return this.recipeData.recipes;
        } else {
          return [];
        }
      },

      tableHeader() {
        return [
          {name: 'name', label: 'Name', sort: true},
          {name: 'tags', label: 'Tags', sort: false},
          {name: 'rating', label: 'Rating', sort: true},
          {name: 'yields', label: 'Yields', sort: false},
          {name: 'total_time', label: 'Time', sort: true},
          {name: 'created_at', label: 'Created', sort: true}
        ]
      },

      totalPages() {
        if (this.recipeData) {
          return this.recipeData.total_pages;
        }
        return 0;
      },

      currentPage() {
        if (this.recipeData) {
          return this.recipeData.current_page;
        }
        return 0;
      }
    },

    methods: {
      changePage(idx) {
        this.search.page = idx;
      },

      setSort(col) {
        if (this.search.sortColumn === col) {
          this.search.sortDirection = this.search.sortDirection === "desc" ? "asc" : "desc";
        } else {
          this.search.sortColumn = col;
          this.search.sortDirection = "asc";
        }
      },

      getList: debounce(function() {
        this.loadResource(
          api.getRecipeList(this.search.page, this.search.per, this.search.sortColumn, this.search.sortDirection, this.search.name, this.search.tags, data => this.recipeData = data)
        );
      }, 500, {leading: true, trailing: true}),

      formatRecipeTime(total, active) {
        let str = "";

        if (total && total > 0) {
          str += total;
        }

        if (active && active > 0) {
          if (str.length) {
            str += " (" + active + ")";
          } else {
            str += active;
          }
        }

        return str;
      }
    },

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

    components: {
    }
  }

</script>