<template>
  <div class="ui-popup-notifications">
    <ui-notification-item-popup
      v-for="notification in popupNotifications"
      @close="close"
      :key="notification.id"
      :notification-id="notification.id"
      :duration="notificationDuration"
    >
      <ui-notification-item-dark :notification="notification" dark />
    </ui-notification-item-popup>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import UiNotificationItemPopup from './item/UiNotificationItemPopup.vue'
import NotificationsStore, {
  getNotificationsStore,
} from './stores/NotificationsStore'
import NotificationsConfigStore, {
  getNotificationsConfigStore,
} from './stores/NotificationsConfigStore'
import UiNotificationItemDark from './item/UiNotificationItemDark.vue'

@Component({
  inheritAttrs: false,
  components: {
    UiNotificationItemDark,
    UiNotificationItemPopup,
  },
})
export default class UiPopupNotifications extends Vue {
  notificationStore!: NotificationsStore
  notificationsConfigStore!: NotificationsConfigStore

  get maxNotificationsCount(): number {
    return this.notificationsConfigStore.notificationsCount
  }

  get notificationDuration(): number {
    return this.notificationsConfigStore.notificationDuration
  }

  created() {
    this.notificationStore = getNotificationsStore(this.$store)
    this.notificationsConfigStore = getNotificationsConfigStore(this.$store)
  }

  mounted() {
    this.$root.$el.append(this.$el)
  }

  destroyed() {
    if (this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el)
    }
  }

  get popupNotifications() {
    if (
      this.notificationStore.popupNotifications.length <=
      this.maxNotificationsCount
    ) {
      return this.notificationStore.popupNotifications
    }

    return this.notificationStore.popupNotifications.splice(
      0,
      this.maxNotificationsCount
    )
  }

  close(notificationId: number) {
    this.notificationStore.removePopupNotification(notificationId)
  }
}
</script>
