<template>
  <q-infinite-scroll @load="onLoad" ref="infinityScroll" :offset="250">
    <slot></slot>
    <template v-if="!isLoadedAllNotification" v-slot:loading>
      <div class="flex justify-center q-pt-sm">
        <q-spinner-dots style="font-size: 40px !important;" color="primary" />
      </div>
    </template>
  </q-infinite-scroll>
</template>

<script lang="ts">
import { Component, Ref, Vue, Watch } from 'vue-property-decorator'
import NotificationsStore, {
  getNotificationsStore,
} from './stores/NotificationsStore'
import { QInfiniteScroll, QSpinnerDots } from 'quasar'

@Component({
  components: { QInfiniteScroll, QSpinnerDots },
  inheritAttrs: false,
})
export default class UiNotificationsScroll extends Vue {
  notificationStore: NotificationsStore | null = null

  @Ref('infinityScroll') infinityScroll!: { reset: Function }

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

  get currentType(): string | null {
    return this.notificationStore?.currentType || null
  }

  get isLoadedAllNotification() {
    if (!this.notificationStore) {
      return false
    }

    return (
      this.notificationStore.notifications.length >=
      this.notificationStore.currentTypeNotificationCount
    )
  }

  async onLoad(index: number, done: Function) {
    if (this.isLoadedAllNotification) {
      done(true)

      return
    }

    const store = this.notificationStore as NotificationsStore
    await store.loadNotificationsOnScroll()

    done(this.isLoadedAllNotification)
  }

  @Watch('currentType')
  resetScroll() {
    this.infinityScroll.reset()
  }
}
</script>
