<template>
  <div>
    <v-row>
      <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
      <v-col rows="12">
        <div
          class="text-center text-h4"
          v-if="obj.length == 0"
          data-cy="notifications"
        >
          <span>{{ $ay.t("NoData") }}</span>
        </div>
        <v-timeline
          :dense="$vuetify.breakpoint.smAndDown"
          v-if="obj.length > 0"
          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 class="mt-4" v-if="i.message">
                  <pre>{{ i.message }}</pre>
                </div>
              </v-card-text>

              <v-card-actions>
                <v-btn text @click="deleteItem(i)">{{ $ay.t("Delete") }}</v-btn>
                <v-btn
                  text
                  @click="openSubscription(i)"
                  v-if="i.eventType != 27"
                  >{{ $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 {
  async created() {
    let 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);
  },
  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()
    };
  },
  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) {
      //prompt
      //delete

      let vm = this;
      try {
        let dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }

        window.$gz.form.deleteAllErrorBoxErrors(vm);
        let res = await window.$gz.api.remove(
          `notify/${item.id}`,
          this.selectedItems
        );
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        }
        await this.getDataFromApi();
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      }
    },

    async getDataFromApi() {
      let vm = this;

      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);

        let res = await window.$gz.api.get("notify/app-notifications");

        if (res.error) {
          //Not found?
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //pre-make the display list object
          //source object:
          //[ { "id": 1, "concurrency": 18835104, "userId": 1, "created": "2020-07-20T19:35:49.665888Z", "ayaType": 2,
          // "objectId": 101, "eventType": 2, "notifySubscriptionId": 1, "message": null, "fetched": true } ]
          //display object:
          //{event:"",objectname:"",objecttype:null,icon:null,eventdate:null,openurl:null,suburl:null,eventid}

          let temp = res.data;

          //Nice touch to show super faded just before deletion but don't have time for this at the moment
          // let dtNow = window.$gz.DateTime.local();
          // let dtToday = window.$gz.DateTime.local(
          //   dtNow.year,
          //   dtNow.month,
          //   dtNow.day
          // );
          // let dtPrecipice = dtToday.plus({ days: -85 }).toUTC();

          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"] = vm.selectLists.eventTypes.find(
              z => z.id == temp[i].eventType
            ).name;

            temp[i]["uiayatype"] = vm.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 = vm.$ay.t("Server");
            }

            // if (temp[i].message && temp[i].message.includes("\n")) {
            //   temp[i].message = temp[i].message.replace("\n", "<br/>");
            // }

            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 = "";
            }
          }

          vm.obj = [...temp];

          //modify the menu as necessary
          generateMenu(vm);
          //Update the form status
          window.$gz.form.setFormState({
            vm: vm,
            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
          let 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, vm));
          }
          window.$gz.store.commit("setNewNotificationCount", status.data);
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    }
  }
};

/////////////////////////////
//
//
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 "refresh":
        await m.vm.getDataFromApi();
        break;
      // case "directnotify":
      //   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: "$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(vm);
  await populateSelectionLists(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  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>
