<template>
    <div>
        <!-- Slot for header -->
        <slot name="header" />

        <template v-for="(items, sort_key) in sortedData">
            <slot name="category-header" v-bind:sort_key="sort_key" />
            <slot name="card" v-bind:items="items" />
        </template>
    </div>
</template>

<script>
import { AjaxRequests } from "@/mixins/ajaxRequests";
import { Workflow } from "@/mixins/workflow";

/**
 * Appup Gridview component which can be used to display Grid items
 */
export default {
  name: "appup-card",
  mixins: [AjaxRequests, Workflow],
  props: {
    /**
     * Fetch data with url
     */
    url: {
      type: String,
      required: false
    },
    /**
     * Action items for grid item
     *
     * 'view','edit','delete'
     */
    actions: {
      type: Array,
      required: false
    },
    sortKey: {
      type: String,
      required: false
    },
    /**
     * URL to deserialize the grid initially.
     */
    preload: {
      type: String,
      required: false
    }
   
  },
  components: {},
  data() {
    return {
      data: [],
      sortedData: {}
    };
  },
  methods: {
    clickAction(item, action) {
      if (action === "edit") {
        this.$router.push(this.edit.route + "/" + item[this.edit.key]);
      } else if (action == "delete") {
        console.log("delete id ", item[this.edit.key]);
      } else {
        return;
      }
    }
  },
  watch: {
    data(newVal, oldVal) {
      console.log("Sort key " + this.sortKey);

      // If sort key is there
      if (this.sortKey && this.data) {
        var self = this;
        this.sortedData = _.groupBy(this.data, function(data) {
          return data[self.sortKey];
        });
      } else {
        // console.log("no sort key");
        this.sortedData.test = this.data;
      }
      // console.log(this.sortedData);
    }
  },
  mounted() {
    if (this.preload) this.start(this.preload);
  }
};
</script>