import { Component, Inject, Vue } from 'vue-property-decorator'
import { MessageThread } from '@/widgets/messages/types/MessageThread'
import { GetThreadsPayload } from '@/widgets/messages/services/ThreadService'
import MessageModule from '@/widgets/messages/modules/MessageModule'
import { hashNavRoutes } from '@/widgets/messages/router/hashRoutes'

@Component
export default class BaseThreadsPage extends Vue {
  @Inject('MessageModule')
  messageModule!: MessageModule

  isInitialLoading = false
  lastLoadedTasksLength = 0

  get initialPayload(): GetThreadsPayload | null {
    return null
  }

  get threads(): MessageThread[] {
    return this.messageModule.threads
  }

  async infinityLoad(index: number, done: Function) {
    const threads = await this.messageModule.infinityLoadThreads(
      this.initialPayload as GetThreadsPayload
    )

    done(threads.length === 0)
  }

  get isDisableInfinity() {
    return this.isInitialLoading || !this.threads.length
  }

  initialLoad() {
    this.isInitialLoading = true

    return this.messageModule
      .loadThreads(this.initialPayload || undefined)
      .finally(() => (this.isInitialLoading = false))
  }

  toCreateRoute() {
    return this.$router.push({ name: hashNavRoutes.createThread.compile() })
  }

  toIndexRoute() {
    return this.$router.push({ hash: hashNavRoutes.index.compile() })
  }

  activated() {
    this.initialLoad()
  }

  deactivated() {
    this.lastLoadedTasksLength = 0
    this.isInitialLoading = false
  }
}
