<template>
  <v-snackbar
    data-cy="gznotify"
    :value="isVisible"
    :color="currentNotification.type"
    multi-line
    :timeout="currentNotification.timeout"
  >
    <v-alert :type="currentNotification.type" mode="out-in">
      {{ currentNotification.message }}
    </v-alert>

    <v-btn
      v-if="currentNotification.helpUrl"
      data-cy="gznotify:morebutton"
      text
      @click="helpClick()"
    >
      {{ this.$root.$gz.translation.get("More") }}
    </v-btn>
  </v-snackbar>
</template>
<script>
const DEFAULT_NOTIFY_OPTIONS = { type: "info", timeout: 3000 };
export default {
  data: () => ({
    isVisible: false,
    processing: false,
    notificationQueue: [],
    currentNotification: {
      type: "info", //one of success, info, warning, and error, see v-alert docs for more info
      timeout: 3000,
      message: null,
      helpUrl: null
    }
  }),
  methods: {
    addNotification(options) {
      if (!options.message) {
        return;
      }
      if (!options.type) {
        options.type = DEFAULT_NOTIFY_OPTIONS.type;
      }
      if (!options.timeout) {
        options.timeout = DEFAULT_NOTIFY_OPTIONS.timeout;
      }
      this.notificationQueue.push(options);
      //trigger the notification queue handler if it isn't already in action
      if (!this.processing) {
        this.handleNotifications();
      }
    },
    handleNotifications() {
      this.processing = true;
      //Process the queue
      if (this.notificationQueue.length > 0) {
        //Move the next item into the current slot
        this.currentNotification = this.notificationQueue.shift();
        //If don't use nextTick then don't get all visible when multiple in sequence
        this.$nextTick(() => {
          this.isVisible = true;
        });
        //Show it for the designated time before moving on to the next

        setTimeout(() => {
          this.isVisible = false;
          //recurse
          this.handleNotifications();
        }, this.currentNotification.timeout);
      } else {
        this.processing = false;
        return;
      }
    },
    helpClick() {
      window.open(this.currentNotification.helpUrl, "_blank");
    }
  }
};
</script>
