<template>
  <widget-page
    @load="infinityLoad"
    :disable="isDisableInfinity"
    :is-loading="isInitialLoading"
  >
    <threads v-if="threads.length" :threads="threads" />
    <widget-page-state
      v-if="!isInitialLoading && !threads.length"
      @submit="toIndexRoute"
      has-btn
      submit-label="Все сообщения"
      :icon="icon"
      :title="label"
    />
  </widget-page>
</template>

<script lang="ts">
import { Component } from 'vue-property-decorator'
import { GetThreadsPayload } from '@/widgets/messages/services/ThreadService'
import { MessageFilterType } from '@/widgets/messages/types/CountingMessages'
import WidgetPage from '@/widgets/base/components/widget-page/WidgetPage.vue'
import Threads from '@/widgets/messages/components/Threads.vue'
import WidgetPageState from '@/widgets/base/components/widget-page/WidgetPageState.vue'
import BaseThreadsPage from '@/widgets/messages/pages/BaseThreadsPage'

@Component({
  components: { WidgetPageState, Threads, WidgetPage },
  beforeRouteUpdate(this: IndexPage, to, from, next) {
    next()

    this.isInitialLoading = true

    return this.messageModule
      .loadThreads({
        ...this.initialPayload,
        type: to.params.type as MessageFilterType,
      })
      .finally(() => (this.isInitialLoading = false))
  },
})
export default class IndexPage extends BaseThreadsPage {
  get initialPayload(): GetThreadsPayload {
    return {
      type: (this.$route.params.type as MessageFilterType) || undefined,
    }
  }

  get icon(): string {
    if (this.initialPayload.type) {
      const icons: Partial<{ [key in MessageFilterType]: string }> = {
        [MessageFilterType.favoriteThreads]: 'la la-bookmark',
        [MessageFilterType.openedThreads]: 'la la-inbox',
        [MessageFilterType.subscribedThread]: 'la la-user-check',
      }

      return icons[this.initialPayload.type] as string
    }

    return 'la la-home'
  }

  get label(): string {
    if (this.initialPayload.type) {
      const icons: Partial<{ [key in MessageFilterType]: string }> = {
        [MessageFilterType.favoriteThreads]: 'В избранном ничего нет',
        [MessageFilterType.openedThreads]: 'Похоже все сообщения обработаны',
        [MessageFilterType.subscribedThread]: 'Вы не подписаны ни на одну тему',
      }

      return icons[this.initialPayload.type] as string
    }

    return ''
  }

  destroyed() {
    this.messageModule.setThreads([])
  }
}
</script>
