<template>
  <widget-layout :is-loading="isLoading">
    <template #bar>
      <tasks-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 { RouteNames } from '@/widgets/tasks/router/routeNames'
import { ManagerModule } from '@/widgets/tasks/modules/ManagerModule'
import { TaskModule } from '@/widgets/tasks/modules/TaskModule'
import { CategoryModule } from '@/widgets/tasks/modules/CategoryModule'
import WidgetLayout from '@/widgets/base/components/widget-layout/WidgetLayout.vue'
import TasksBar from '@/widgets/tasks/components/bar/TasksBar.vue'
import { TaskUserModule } from '@/widgets/tasks/modules/TaskUserModule'
import { AuthService } from '@/services/AuthService'
import { Manager } from '@/types/Manager'

@Component({
  components: { TasksBar, WidgetLayout },
})
export default class TasksLayout extends Vue {
  @Provide('ManagerModule')
  managerModule: ManagerModule = getModule(ManagerModule, this.$store)

  @Provide('TaskModule')
  taskModule: TaskModule = getModule(TaskModule, this.$store)

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

  @Provide('CategoryModule')
  categoryModule: CategoryModule = getModule(CategoryModule, this.$store)

  @Prop(String)
  orderName?: string

  isLoading = false

  async created() {
    this.isLoading = true

    if (this.orderName && this.$route.name !== RouteNames.orderTasks) {
      this.taskModule.setOrderName(this.orderName)

      await this.$router.push({
        name: RouteNames.orderTasks,
        params: { orderName: this.orderName },
      })
    }

    const token = await AuthService.getAuthToken(
      process.env.TASKS_API_URL as string
    )

    await Promise.all([
      this.userModule.loadUser(),
      this.managerModule.loadManagers(),
      this.categoryModule.loadCategories(),
      this.categoryModule.loadCounting(),
    ])

    const user = this.userModule.user as Manager

    if (user) {
      this.taskModule.initWebsocket({ authToken: token, user })
      this.categoryModule.initWebsocket({ authToken: token, user })
    }

    this.isLoading = false
  }
}
</script>
