<template>
  <div>

    <app-expand-transition name="fade">
      <task-item-edit @save="save" :task-item="newItem" v-if="showAddItem" ref="itemEdit"></task-item-edit>
    </app-expand-transition>

    <table class="table">
      <thead>
      <tr>
        <th></th>
        <th>Name</th>
        <th>Quantity</th>
        <th>
          <button class="button" @click="toggleShowAddItem">{{ showAddItem ? 'Done' : 'New Item' }}</button>
        </th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="i in taskItems" :key="i.id" @click="toggleItem(i)">
        <td>
          <div class="check">
            <app-icon v-if="i.completed" icon="check"></app-icon>
          </div>
        </td>
        <td>{{ i.name }}</td>
        <td>{{ i.quantity }}</td>
        <td></td>
      </tr>
      <tr v-if="taskItems.length === 0">
        <td colspan="4">
          No Items
        </td>
      </tr>
      </tbody>
    </table>

  </div>
</template>

<script>

  import * as Errors from '../lib/Errors';
  import { mapActions } from "vuex";
  import cloneDeep from "lodash/cloneDeep";

  import TaskItemEdit from "./TaskItemEdit";

  const newItemTemplate = function(listId) {
    return {
      task_list_id: listId,
      name: '',
      quantity: '',
      completed: false
    };
  };

  export default {
    props: {
      taskList: {
        required: true,
        type: Object
      }
    },

    data() {
      return {
        showAddItem: false,
        newItem: null,
        newItemValidationErrors: {}
      };
    },

    computed: {
      taskItems() {
        const top = [];
        const bottom = [];
        const list = (this.taskList ? this.taskList.task_items : []);

        for (let i of list) {
          if (!i.completed) {
            top.push(i);
          } else {
            bottom.push(i);
          }
        }

        return top.concat(bottom);
      }
    },

    methods: {
      ...mapActions([
        'createTaskItem',
        'updateTaskItem'
      ]),

      save() {
        this.loadResource(
          this.createTaskItem(this.newItem)
            .then(() => {
              this.newItem = newItemTemplate(this.taskList.id);
              this.$refs.itemEdit.focus();
            })
            .catch(Errors.onlyFor(Errors.ApiValidationError, err => this.newItemValidationErrors = err.validationErrors()))
        )
      },

      toggleItem(i) {
        const item = cloneDeep(i);
        item.completed = !item.completed;
        this.loadResource(
          this.updateTaskItem(item)
        )
      },

      toggleShowAddItem() {
        this.newItem = newItemTemplate(this.taskList.id);
        this.showAddItem = !this.showAddItem;
      }

    },

    components: {
      TaskItemEdit
    }
  }

</script>

<style lang="scss" scoped>

  .columns {
    margin-top: 0;
    margin-bottom: 0;
  }

  .column {
    padding-top: 0;
    padding-bottom: 0;
    margin-top: 0;
    margin-bottom: 0;
  }

</style>