<template>
  <loader>
    <div v-if="$route.meta.store.items">
      <header class="page-header pt-4 pb-3">
        <h1>
          {{capitalizedItemName}} Overzicht
        </h1>

        <span class="page-header-buttons" v-if="canCreate">
          <router-link :to="{ name: 'create-' + $route.meta.itemName, query: $route.query }" class="btn btn-primary" v-if="singleNewItem">
            <span class="icon-plus"></span>
            {{capitalizedItemName}} toevoegen
          </router-link>
          <router-link v-else v-for="(key, type) in $route.meta.newItem" :key="key" class="btn btn-primary"
            :to="{ name: 'create-type-' + $route.meta.itemName, query: Object.assign({}, $route.query, { type: type }) }">
            <span class="icon-plus"></span>
            {{type}}
          </router-link>
        </span>
      </header>

      <listing :items="$route.meta.store.items" :fields="fields" :action="navigateToEditor" :schema="$route.meta.store.schema" :custom-fields="customFields"></listing>
    </div>
  </loader>
</template>

<script>
  import { permissionStore } from '../tools/permission-store.js'
  import loader from '../shared/loader.vue';
  import listing from '../shared/listing.vue';
  import linkToEditor from '../schema/fields/link-to-editor.vue';

  export default {
    name: 'crud-overview',
    computed: {
      isLoading() { return this.$route.meta.store.isLoading },
      fields() {
        return this.$route.meta.fields instanceof Array
          ? this.$route.meta.store.fieldsObjectForProps(this.$route.meta.fields)
          : this.$route.meta.fields || this.$route.meta.store.fields;
      },
      singleNewItem() { return this.$route.meta.newItem instanceof Function; },
      capitalizedItemName() {
        return this.$route.meta.store.schema.title || this.$route.meta.itemName.replace(/\b\w/g, c => c.toUpperCase());
      },
      customFields() {
        return {...this.$route.meta.customFields, Editor: this.$options.components.linkToEditor};
      },
      canCreate() {
        return !this.$route.meta.store.schema.preventCreate && permissionStore.canCreate(this.$route.meta.itemName)
      }
    },
    watch: {
      '$route.meta.store.state.fetchItemsError'(error) {
        if (error) {
          this.$store.dispatch('alerts/addError', error);
        }
      }
    },
    mounted() {
      // show error when user is entering the page again after the first visit
      if (this.$route.meta.store.state.fetchItemsError) {
        this.$store.dispatch('alerts/addError', this.$route.meta.store.state.fetchItemsError);
      }
    },
    methods: {
      navigateToEditor(item) {
        this.$router.push({
          name: this.$route.meta.itemName + '-editor',
          params: { id: item.id },
          query: this.$route.query
        });
      }
    },
    components: {
      loader,
      listing,
      linkToEditor
    }
  }
</script>
