<template>
  <div>
    <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
    <v-data-table
      :headers="headers"
      :items="obj"
      class="elevation-1"
      :disable-pagination="true"
      :disable-filtering="true"
      hide-default-footer
      @click:row="rowClick"
      :header-props="{ sortByText: $ay.t('Sort') }"
      data-cy="subsTable"
      :no-data-text="$ay.t('NoData')"
    >
    </v-data-table>
  </div>
</template>

<script>
const FORM_KEY = "notification-subscriptions";
export default {
  async created() {
    let vm = this;
    try {
      await initForm(vm);
      vm.formState.readOnly = false;
      vm.formState.ready = true;
      window.$gz.eventBus.$on("menu-click", clickHandler);
      await vm.getDataFromApi();
      vm.formState.loading = false;
    } catch (err) {
      vm.formState.ready = true;
      window.$gz.errorHandler.handleFormError(err, vm);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  data() {
    return {
      obj: [],
      headers: [],
      formState: {
        ready: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.fullRightsObject() //users always have full rights to their own notification subscriptions
    };
  },
  methods: {
    rowClick(item) {
      //nav to item.id
      window.$gz.eventBus.$emit("openobject", {
        type: window.$gz.type.NotifySubscription,
        id: item.id
      });
    },
    async getDataFromApi() {
      let vm = this;
      vm.formState.loading = true;

      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get("notify-subscription/list");

        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          if (res.data) {
            /*       z.Id,
                z.UserId,
                z.EventType,
                z.AyaType,
                z.DeliveryMethod,
                z.DeliveryAddress,
                z.Tags,
                info */
            let ret = [];
            for (let i = 0; i < res.data.length; i++) {
              let o = res.data[i];
              ret.push({
                id: o.id,
                eventType: window.$gz.enums.get("NotifyEventType", o.eventType),
                info: o.info,
                ayaType: window.$gz.enums.get("coreview", o.ayaType),
                deliveryMethod: window.$gz.enums.get(
                  "NotifyDeliveryMethod",
                  o.deliveryMethod
                ),
                deliveryAddress: o.deliveryAddress,
                tags: window.$gz.util.formatTags(o.tags)
              });
            }

            vm.obj = ret;
          } else {
            vm.obj = [];
          }

          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
          generateMenu(vm);
        }
      } catch (error) {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    }
  }
};

/////////////////////////////
//
//
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: "home-notify-subscription",
          params: { recordid: 0 }
        });
        break;

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

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "$ayiBullhorn",
    title: "NotifySubscriptionList",
    helpUrl: "home-notify-subscriptions",
    menuItems: [],
    formData: {
      ayaType: window.$gz.type.NotifySubscription
    }
  };

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

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
  await cacheEnums(vm);
  await createTableHeaders(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations([
    "NotifyEventType",
    "ID",
    "AyaType",
    "NotifyDeliveryMethod",
    "NotifyDeliveryAddress",
    "Tags"
  ]);
}

//////////////////////
//
//
async function cacheEnums(vm) {
  //ensure the enum values required are pre-fetched
  await window.$gz.enums.fetchEnumList("NotifyEventType");
  await window.$gz.enums.fetchEnumList("NotifyDeliveryMethod");
  await window.$gz.enums.fetchEnumList("coreview");
}

//////////////////////
//
//
async function createTableHeaders(vm) {
  vm.headers = [
    { text: vm.$ay.t("ID"), value: "id" },
    { text: vm.$ay.t("NotifyEventType"), value: "eventType" },
    { text: vm.$ay.t("AyaType"), value: "ayaType" },
    { value: "info" },
    { text: vm.$ay.t("NotifyDeliveryMethod"), value: "deliveryMethod" },
    { text: vm.$ay.t("NotifyDeliveryAddress"), value: "deliveryAddress" },
    { text: vm.$ay.t("Tags"), value: "tags" }
  ];
}
</script>
