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

<script lang="ts">
import { Component, Prop, Provide, Vue } from 'vue-property-decorator'
import { NotificationsConfigModule, NotificationsModule } from '@/widgets'
import { getModule } from 'vuex-module-decorators'
import PopupItemWrapper from '@/widgets/notifications/components/popup-notifications/PopupItemWrapper.vue'
import UiPopupNotificationsItem from '@/widgets/notifications/components/popup-notifications/UiPopupNotificationsItem.vue'

@Component({
  inheritAttrs: false,
  components: { UiPopupNotificationsItem, PopupItemWrapper },
})
export default class UiPopupNotifications extends Vue {
  @Prop({ type: String, required: true })
  userId!: string

  @Provide('NotificationsModule')
  notificationStore = getModule(NotificationsModule, this.$store)

  @Provide('NotificationsConfigModule')
  notificationsConfigStore = getModule(NotificationsConfigModule, this.$store)

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

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

  mounted() {
    this.$root.$el.append(this.$el)
    this.notificationStore.initWebsocket(this.userId)
  }

  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>
