<template>
  <widget-page
    @load="infinityLoad"
    :disable="isDisableInfinity"
    :is-loading="isInitialLoading"
  >
    <ui-notification-list
      v-if="notifications.length"
      :notifications="notifications"
    />
    <widget-page-state
      v-if="!isInitialLoading && !notifications.length"
      :icon="isInitialLoading ? 'las la-hourglass-half' : 'las la-coffee'"
      :title="isInitialLoading ? 'Немного подождите....' : 'Кофе тайм'"
    />
  </widget-page>
</template>

<script lang="ts">
import { Component, Inject, Prop, Vue } from 'vue-property-decorator'
import { Route } from 'vue-router'
import NotificationsModule from '@/widgets/notifications/modules/NotificationsModule'
import WidgetPageState from '@/widgets/base/components/widget-page/WidgetPageState.vue'
import WidgetPage from '@/widgets/base/components/widget-page/WidgetPage.vue'
import UiNotificationList from '@/widgets/notifications/components/notifications-list/UiNotificationList.vue'
import { NotificationCode } from '@/widgets/notifications/types/NotificationEvent'

@Component({
  components: { UiNotificationList, WidgetPage, WidgetPageState },
  beforeRouteUpdate(this: IndexPage, to, from, next) {
    this.setCodesFromRoute(to)
    this.notificationsModule.loadNotifications()

    next()
  },
})
export default class IndexPage extends Vue {
  @Inject('NotificationsModule')
  notificationsModule!: NotificationsModule

  @Prop(String)
  type!: string

  get notifications() {
    return this.notificationsModule.notifications
  }

  get isDisableInfinity() {
    return (
      this.notifications.length === 0 ||
      this.isInitialLoading ||
      this.notifications.length === this.notificationsModule.totalCount
    )
  }

  get isInitialLoading() {
    return this.notificationsModule.isLoading
  }

  setCodesFromRoute(route: Route) {
    this.notificationsModule.setCurrentCodes(
      (route.query?.codes || []) as NotificationCode[]
    )
  }

  async infinityLoad(index: number, done: Function) {
    await this.notificationsModule.loadNotificationsOnScroll()

    done()
  }

  activated() {
    this.setCodesFromRoute(this.$route)
    this.notificationsModule.loadNotifications()
  }
}
</script>
