<template>
  <v-row v-if="this.formState.ready">
    <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
    <v-col cols="12">
      <v-btn @click="getDataFromApi" class="mb-6">
        <v-icon>$ayiSync</v-icon>
      </v-btn>

      <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') }"
      >
        <template v-slot:[`item.actions`]="{ item }">
          <v-icon small class="mr-2" @click="deleteItem(item)">
            $ayiTrashAlt
          </v-icon>
        </template></v-data-table
      >
    </v-col>
  </v-row>
</template>

<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
////////////////////////////////////////////////////////////////////////////////////////////////////////////

const FORM_KEY = "ops-notify-queue";

export default {
  async created() {
    let vm = this;
    try {
      await initForm(vm);

      vm.rights = window.$gz.role.getRights(
        window.$gz.type.OpsNotificationSettings
      );
      vm.formState.readOnly = !vm.rights.change;
      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);
    }
  },
  data() {
    return {
      obj: [],
      rawObj: [],
      headers: [],
      formState: {
        ready: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject(),

      //cache display format stuff
      timeZoneName: window.$gz.locale.getBrowserTimeZoneName(),
      languageName: window.$gz.locale.getBrowserLanguages(),
      hour12: window.$gz.locale.getHour12()
    };
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    async deleteItem(item) {
      let vm = this;
      try {
        let dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }

        //do the delete
        vm.formState.loading = true;

        window.$gz.form.deleteAllErrorBoxErrors(vm);
        let res = await window.$gz.api.remove(`notify-event/${item.id}`);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //refresh
          await vm.getDataFromApi();
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        vm.formState.loading = false;
      }
    },
    async getDataFromApi() {
      let vm = this;
      vm.formState.loading = true;
      let url = "notify/queue";
      window.$gz.form.deleteAllErrorBoxErrors(vm);
      try {
        let res = await window.$gz.api.get(url);

        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.eventBus.$emit("notify-error", vm.$ay.t("ErrorAPI2010"));
            window.$gz._.delay(function() {
              vm.$router.go(-1);
            }, 2000);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          if (res.data) {
            vm.rawObj = res.data;

            /*{"data":[{"id":6,"created":"2020-07-24T17:52:05.777883Z","eventDate":"2020-07-24T17:52:05.777886Z","deliverAfter":"2021-07-24T17:52:05.777886Z",
"userId":1,"eventType":10,"ayaType":2,"name":"Small Frozen Chicken 117-1"}]} */
            let ret = [];
            for (let i = 0; i < res.data.length; i++) {
              let o = res.data[i];
              ret.push({
                id: o.id,
                created: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
                  o.created,
                  this.timeZoneName,
                  this.languageName,
                  this.hour12
                ),
                eventDate: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
                  o.eventDate,
                  this.timeZoneName,
                  this.languageName,
                  this.hour12
                ),
                deliverAfter: window.$gz.locale.utcDateToShortDateAndTimeLocalized(
                  o.deliverAfter,
                  this.timeZoneName,
                  this.languageName,
                  this.hour12
                ),
                eventType: window.$gz.enums.get("NotifyEventType", o.eventType),
                ayaType: window.$gz.enums.get("core", o.ayaType),
                name: o.name,
                userId: o.userId
              });
            }

            vm.obj = ret;
          } else {
            vm.rawObj = [];
            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);
      }
    }
  }
};

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: true,
    icon: "$ayiBullhorn",
    title: "NotifyQueue",
    helpUrl: "form-ops-notify-queue",
    formData: {
      ayaType: window.$gz.type.ServerJob
    },
    menuItems: [
      //   {
      //     title: "Copy",
      //     icon: "$ayiCopy",
      //     surface: false,
      //     key: FORM_KEY + ":copylog",
      //     vm: vm
      //   }
    ]
  };

  //   if (vm.rights.change) {
  //     menuOptions.menuItems.push({
  //       title: "OpsTestJob",
  //       icon: "$ayiRobot",
  //       surface: false,
  //       key: FORM_KEY + ":TEST_JOB",
  //       vm: vm
  //     });
  //   }

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

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      //   case "copylog":
      //     //put the log info on the clipboard:
      //     window.$gz.util.copyToClipboard(
      //       "SERVER JOBS LOG\n" + JSON.stringify(m.vm.rawObj, null, 1)
      //     );
      //     break;
      //   case "TEST_JOB":
      //     m.vm.testJob();
      //     break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

/////////////////////////////////
//
//
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",
    "EventCreated",
    "AyaType",
    "Name",
    "User",
    "DeliverAfter",
    "NotifyQueue"
  ]);
}

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

//////////////////////
//
//
async function createTableHeaders(vm) {
  vm.headers = [
    {
      text: vm.$ay.t("EventCreated"),
      align: "start",
      value: "created"
    },
    { text: vm.$ay.t("DeliverAfter"), value: "deliverAfter" },
    { text: vm.$ay.t("NotifyEventType"), value: "eventType" },
    { text: vm.$ay.t("AyaType"), value: "ayaType" },
    { text: vm.$ay.t("Name"), value: "name" },
    { text: vm.$ay.t("User"), value: "user" },
    { text: "", value: "actions", sortable: false }
  ];
}
</script>
