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

<script lang="ts">
import { Component, Prop, Provide, Vue } 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 WidgetLayout from '@/widgets/base/components/widget-layout/WidgetLayout.vue'
import MessageModule from '@/widgets/messages/modules/MessageModule'
import CountingMessagesModule from '@/widgets/messages/modules/CountingMessagesModule'
import MessagesBar from '@/widgets/messages/components/bar/MessagesBar.vue'
import { AuthService } from '@/services/AuthService'

@Component({
  components: { MessagesBar, WidgetLayout },
})
export default class MessagesLayout extends Vue {
  @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

  async created() {
    this.isLoading = true

    if (this.orderName) {
      this.messageModule.setOrderName(this.orderName)
    }

    const token = await AuthService.getAuthToken(
      process.env.MESSAGES_API_URL ?? ''
    )

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

    await this.messageModule.initWebsocket(token)

    this.isLoading = false
  }
}
</script>
