<template>
  <widget-layout :is-loading="isLoading">
    <template>
      <component :is="page" v-bind="$attrs" />
    </template>

    <template #bar>
      <messages-bar :order-name="orderName" />
    </template>
  </widget-layout>
</template>

<script lang="ts">
import { Component, Prop, Provide, Watch } from 'vue-property-decorator'
import { getModule } from 'vuex-module-decorators'
import { ManagerModule } from '@/widgets/messages/modules/ManagerModule'
import { MessageUserModule } from '@/widgets/messages/modules/MessageUserModule'
import MessageModule from '@/widgets/messages/modules/MessageModule'
import CountingMessagesModule from '@/widgets/messages/modules/CountingMessagesModule'
import WidgetLayout from '@/widgets/base/components/widget-layout/WidgetLayout.vue'
import MessagesBar from '@/widgets/messages/components/bar/MessagesBar.vue'
import { BaseWidgetLayout } from '@/widgets/base/BaseWidgetLayout'
import { PageName } from '@/widgets/messages/router/pageNames'
// Page components
import SearchPage from '@/widgets/messages/pages/SearchPage.vue'
import OrderThreadsPage from '@/widgets/messages/pages/OrderThreadsPage.vue'
import CreateThreadPage from '@/widgets/messages/pages/CreateThreadPage.vue'
import ThreadPage from '@/widgets/messages/pages/ThreadPage.vue'
import IndexPage from '@/widgets/messages/pages/IndexPage.vue'

const pageComponents = {
  search: SearchPage,
  orderThreads: OrderThreadsPage,
  createThread: CreateThreadPage,
  thread: ThreadPage,
  index: IndexPage,
}

@Component({ components: { MessagesBar, WidgetLayout } })
export default class MessagesLayout extends BaseWidgetLayout {
  @Prop({ type: String, required: true })
  pageName!: PageName

  @Prop(String)
  orderName?: string

  @Provide('MessageModule')
  messageModule: MessageModule = getModule(MessageModule, this.$store)

  @Provide('ManagerModule')
  managerModule: ManagerModule = getModule(ManagerModule, this.$store)

  @Provide('MessageUserModule')
  userModule: MessageUserModule = getModule(MessageUserModule, this.$store)

  @Provide('CountingMessagesModule')
  countingModule: CountingMessagesModule = getModule(
    CountingMessagesModule,
    this.$store
  )

  isLoading = false

  get page() {
    return pageComponents[this.pageName]
  }

  async created() {
    this.isLoading = true

    // await this.messageModule.initWebsocket()
    await Promise.all([
      this.userModule.loadUser(),
      this.managerModule.loadManagers(),
      this.messageModule.loadSubjects(),
      this.countingModule.loadCounting(),
    ])

    this.isLoading = false
  }

  @Watch('orderName')
  updateOrderName() {
    const { orderName, messageModule } = this

    if (orderName && orderName !== messageModule.orderName) {
      this.messageModule.setOrderName(orderName)
    }
  }
}
</script>
