<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
      :header-props="{ sortByText: $ay.t('Sort') }"
      data-cy="subsTable"
      :no-data-text="$ay.t('NoData')"
      @click:row="rowClick"
    >
    </v-data-table>
  </div>
</template>
<script>
const FORM_KEY = "customer-notify-subscriptions";
export default {
  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
    };
  },
  async created() {
    const 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);
  },
  methods: {
    rowClick(item) {
      //nav to item.id
      window.$gz.eventBus.$emit("openobject", {
        type: window.$gz.type.CustomerNotifySubscription,
        id: item.id
      });
    },
    async getDataFromApi() {
      const vm = this;
      vm.formState.loading = true;
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        const res = await window.$gz.api.get(
          "customer-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) {
            const ret = [];
            const languageName = window.$gz.locale.getResolvedLanguage();
            const currencyName = window.$gz.locale.getCurrencyName();
            for (let i = 0; i < res.data.length; i++) {
              const o = res.data[i];
              let info = "";
              if (o.status != "") {
                info += o.status;
              }
              if (o.decValue && o.decValue != 0) {
                //currently is only currency for "The Andy" so format as currency
                const t = window.$gz.locale.currencyLocalized(
                  o.decValue,
                  languageName,
                  currencyName
                );
                if (info != "" && t != "") {
                  info += ` - ${t}`;
                }
              }
              if (o.ageValue) {
                const t = window.$gz.locale.durationLocalized(o.ageValue);
                if (info != "" && t != "") {
                  info += ` - ${t}`;
                }
              }
              let eventDisplay = window.$gz.enums.get(
                "NotifyEventType",
                o.eventType
              );
              if (info && info != "") {
                eventDisplay += ` - ${info}`;
              }

              ret.push({
                id: o.id,
                eventType: eventDisplay,
                customerTags: window.$gz.util.formatTags(o.customerTags),
                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;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "new":
        m.vm.$router.push({
          name: "cust-notify-subscription",
          params: { recordid: 0 }
        });
        break;

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

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: true,
    icon: "$ayiBullhorn",
    title: "CustomerNotifySubscriptionList",
    helpUrl: "customer-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();
  await cacheEnums();
  await createTableHeaders(vm);
}

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

//////////////////////
//
//
async function cacheEnums() {
  await window.$gz.enums.fetchEnumList("NotifyEventType");
}

//////////////////////
//
//
async function createTableHeaders(vm) {
  vm.headers = [
    { text: vm.$ay.t("ID"), value: "id" },
    { text: vm.$ay.t("NotifyEventType"), value: "eventType" },
    { text: vm.$ay.t("CustomerTags"), value: "customerTags" },
    { text: vm.$ay.t("Tags"), value: "tags" }
  ];
}
</script>
