<template>
  <div>
    <h1>Tasks</h1>

    <app-dropdown button-class="is-primary" :open="showListDropdown" :label="listSelectLabel" @open="showListDropdown = true" @close="showListDropdown = false">
      <a class="dropdown-item" href="#" v-for="l in taskLists" @click="selectList(l)">{{l.name}}</a>
      <hr class="dropdown-divider" v-if="taskLists.length > 0">
      <div class="dropdown-item">
        <task-list-mini-form :task-list="newList" :validation-errors="newListValidationErrors" @save="saveNewList"></task-list-mini-form>
      </div>
    </app-dropdown>

  </div>
</template>

<script>

  import api from "../lib/Api";
  import * as Errors from '../lib/Errors';
  import TaskListMiniForm from "./TaskListMiniForm";

  const newListTemplate = function() {
    return {
      name: ''
    };
  };

  export default {
    data() {
      return {
        taskLists: [],
        showListDropdown: false,
        currentList: null,
        newList: newListTemplate(),
        newListValidationErrors: {}
      }
    },

    computed: {
      listSelectLabel() {
        if (this.currentList === null) {
          return "Select or Create a List";
        } else {
          return this.currentList.name;
        }
      }
    },

    methods: {
      selectList(l) {
        this.currentList = l;
      },

      saveNewList() {
        this.loadResource(
          api.postTaskList(this.newList)
            .then(() => this.updateData())
            .then(() => { this.newList = newListTemplate(); this.newListValidationErrors = {}; } )
            .catch(Errors.onlyFor(Errors.ApiValidationError, err => this.newListValidationErrors = err.validationErrors()))
        );
      },

      updateData() {
        return this.loadResource(api.getTaskLists(data => this.taskLists = data));
      }
    },

    created() {
      this.updateData()
    },

    components: {
      TaskListMiniForm
    }
  }

</script>

<style lang="scss" scoped>

</style>