<template>
  <div>
    <gz-extensions
      :ayaType="ayType"
      :selectedItems="selectedItems"
      ref="extensions"
    >
    </gz-extensions>
    <gz-data-table
      formKey="widget-list"
      :dataListKey="dataListKey"
      :dataListFilter="dataListFilter"
      :dataListSort="dataListSort"
      :showSelect="rights.change"
      v-on:selection-change="handleSelected"
    >
    </gz-data-table>
  </div>
</template>

<script>
const FORM_KEY = "widget-list";
export default {
  created() {
    this.rights = window.$gz.role.getRights(window.$gz.type.Widget);
    window.$gz.eventBus.$on("menu-click", clickHandler);
    generateMenu(this);
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  data() {
    return {
      currentListViewId: 1,
      dataListKey: "TestWidgetDataList",
      dataListFilter: "",
      dataListSort: "",
      rights: window.$gz.role.defaultRightsObject(),
      ayType: window.$gz.type.Widget,
      selectedItems: []
    };
  },
  methods: {
    handleSelected(selected) {
      this.selectedItems = selected;
    }
  }
};

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "new":
        m.vm.$router.push({
          name: "widget-edit",
          params: { recordid: 0 }
        });
        break;
      case "extensions":
        let res = await m.vm.$refs.extensions.open();
        break;

      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "fa-vial",
    title: "WidgetList",
    helpUrl: "form-ay-data-list-view",
    menuItems: [],
    formData: {
      ayaType: window.$gz.type.Widget
    }
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "New",
      icon: "fa-plus",
      surface: true,
      key: FORM_KEY + ":new",
      vm: vm
    });
  }

  //STUB REPORTS
  //Report not Print, print is a further option
  menuOptions.menuItems.push({
    title: "Report",
    icon: "fa-file-alt",
    key: FORM_KEY + ":report",
    vm: vm
  });

  menuOptions.menuItems.push({
    title: "stub: Last report used",
    icon: "fa-file-alt",
    key: FORM_KEY + ":report:STUBlastusedreportid",
    vm: vm
  });

  menuOptions.menuItems.push({
    title: "Extensions",
    icon: "fa-puzzle-piece",
    key: FORM_KEY + ":extensions",
    vm: vm
  });
  window.$gz.eventBus.$emit("menu-change", menuOptions);
}
</script>
