<template>
  <div>
    <v-row dense>
      <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
      <v-col rows="12">
        <div
          v-if="obj.length == 0"
          class="text-center text-h4"
          data-cy="notifications"
        >
          <span>{{ $ay.t("NoData") }}</span>
        </div>
        <v-timeline
          v-if="obj.length > 0"
          :dense="$vuetify.breakpoint.smAndDown"
          data-cy="notifications"
        >
          <v-timeline-item
            v-for="i in obj"
            :key="i.id"
            fill-dot
            :color="i.fetched ? 'grey lighten-2' : 'primary'"
          >
            <v-card :outlined="$store.state.darkMode">
              <v-card-title
                >{{ i.name
                }}<span v-if="i.ageValueViz.length" class="ml-1">
                  - {{ i.ageValueViz }}</span
                ><span v-if="i.decValueViz.length" class="ml-3">
                  - {{ i.decValueViz }}</span
                ></v-card-title
              >
              <v-card-subtitle
                >{{ i.uicreated }} - {{ i.uievent }}</v-card-subtitle
              >
              <v-card-text
                ><template v-if="i.ayaType != 0">
                  <v-btn large color="primary" text @click="openItem(i)"
                    ><v-icon large left>{{ i.icon }}</v-icon
                    >{{ i.uiayatype }}</v-btn
                  >
                </template>
                <div v-if="i.message" class="mt-4">
                  <pre style="white-space: pre-wrap;">{{ i.message }}</pre>
                </div>
              </v-card-text>

              <v-card-actions>
                <v-btn text @click="deleteItem(i)">{{ $ay.t("Delete") }}</v-btn>
                <v-btn
                  v-if="i.eventType != 27"
                  text
                  @click="openSubscription(i)"
                  >{{ $ay.t("Open") }}</v-btn
                >
              </v-card-actions>
            </v-card>
          </v-timeline-item>
        </v-timeline>
      </v-col>
    </v-row>
  </div>
</template>

<script>
const FORM_KEY = "notifications";
export default {
  data() {
    return {
      selectLists: {
        eventTypes: {},
        ayaTypes: {}
      },
      obj: [],
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject()
    };
  },
  async created() {
    const vm = this;
    try {
      await initForm(vm);

      window.$gz.eventBus.$on("menu-click", clickHandler);
      generateMenu(vm, false);
      await vm.getDataFromApi();
    } catch (err) {
      window.$gz.errorHandler.handleFormError(err, vm);
    } finally {
      vm.formState.ready = true;
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    openItem(item) {
      window.$gz.eventBus.$emit("openobject", {
        type: item.ayaType,
        id: item.objectId
      });
    },
    openSubscription(item) {
      window.$gz.eventBus.$emit("openobject", {
        type: window.$gz.type.NotifySubscription,
        id: item.notifySubscriptionId
      });
    },
    async deleteItem(item) {
      try {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }
        window.$gz.form.deleteAllErrorBoxErrors(this);
        const res = await window.$gz.api.remove(
          `notify/${item.id}`,
          this.selectedItems
        );
        if (res.error) {
          this.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(this);
        }
        await this.getDataFromApi();
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, this);
      }
    },
    async getDataFromApi() {
      try {
        window.$gz.form.deleteAllErrorBoxErrors(this);
        const res = await window.$gz.api.get("notify/app-notifications");
        if (res.error) {
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(this);
          }
          this.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(this);
        } else {
          const temp = res.data;
          const timeZoneName = window.$gz.locale.getResolvedTimeZoneName();
          const languageName = window.$gz.locale.getResolvedLanguage();
          const hour12 = window.$gz.store.state.userOptions.hour12;
          const currencyName = window.$gz.locale.getCurrencyName();
          for (let i = 0; i < temp.length; i++) {
            temp[
              i
            ].uicreated = window.$gz.locale.utcDateToShortDateAndTimeLocalized(
              temp[i].created,
              timeZoneName,
              languageName,
              hour12
            );

            temp[i]["uievent"] = this.selectLists.eventTypes.find(
              z => z.id == temp[i].eventType
            ).name;

            temp[i]["uiayatype"] = this.selectLists.ayaTypes.find(
              z => z.id == temp[i].ayaType
            ).name;

            temp[i].icon = window.$gz.util.iconForType(temp[i].ayaType);

            if (temp[i].name == "~SERVER~") {
              temp[i].name = this.$ay.t("Server");
            }

            temp[i].ageValueViz = window.$gz.locale.durationLocalized(
              temp[i].ageValue
            );

            if (temp[i].decValue != null && temp[i].decValue != 0) {
              if (temp[i].eventType == 23) {
                //the "andy", dollars
                temp[i].decValueViz = window.$gz.locale.currencyLocalized(
                  temp[i].decValue,
                  languageName,
                  currencyName
                );
              } else {
                //it's for now only a meter reading so just keep as a straight up number
                temp[i].decValueViz = temp[i].decValue.toString();
              }
            } else {
              temp[i].decValueViz = "";
            }
          }
          this.obj = [...temp];
          generateMenu(this);
          window.$gz.form.setFormState({
            vm: this,
            dirty: false,
            valid: true,
            loading: false
          });
          //Check the new count and update accordingly
          //this is to ensure that when a user is viewing the latest notifications they don't see the NEW count still in the bell icon in menu since they are viewing them live
          const status = await window.$gz.api.get("notify/new-count");
          if (status.error) {
            //throw new Error(status.error);
            throw new Error(
              window.$gz.errorHandler.errorToString(status, this)
            );
          }
          window.$gz.store.commit("setNewNotificationCount", status.data);
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
      } finally {
        window.$gz.form.setFormState({
          vm: this,
          loading: false
        });
      }
    }
  }
};

/////////////////////////////
//
//
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 "refresh":
        await m.vm.getDataFromApi();
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  const menuOptions = {
    isMain: true,
    icon: "$ayiBell",
    title: "Notifications",
    helpUrl: "home-notifications",
    menuItems: []
  };

  menuOptions.menuItems.push({
    title: "Refresh",
    icon: "$ayiSync",
    surface: true,
    key: FORM_KEY + ":refresh",
    vm: vm
  });

  if (
    !window.$gz.store.getters.isCustomerUser &&
    !window.$gz.store.getters.isSubContractorUser
  ) {
    menuOptions.menuItems.push({
      title: "DirectNotification",
      icon: "$ayiCommentAlt",
      data: "home-notify-direct",
      key: "app:nav"
    });
  }

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}
/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText();
  await populateSelectionLists(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "NotifySubscription",
    "Server",
    "Notifications"
  ]);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  //ensure the pick lists required are pre-fetched
  await window.$gz.enums.fetchEnumList("NotifyEventType");

  vm.selectLists.eventTypes = window.$gz.enums.getSelectionList(
    "NotifyEventType"
  );

  await window.$gz.enums.fetchEnumList("ayatype");
  vm.selectLists.ayaTypes = window.$gz.enums.getSelectionList("ayatype");
}
</script>
