<template>
  <div class="thread-header">
    <div class="full-width">
      <div class="flex no-wrap ui-gap-x-xs q-mb-sm full-width">
        <favorite-toggle :thread="thread" />
        <thread-menu
          @change-order="changeOrder"
          @change-subject="changeSubject"
          :order-name="orderName"
          :thread="thread"
          :subjects="subjects"
        />
        <thread-subject-chip :thread="thread" :order-name="orderName" />
        <thread-manager-avatars
          @click="showManagers"
          :selected-uids="thread.managerUids"
          :thread="thread"
          class="q-ml-auto"
        />
      </div>
      <thread-title :thread="thread" />
    </div>
  </div>
</template>

<style lang="sass" scoped>
.thread-header
  padding: 16px
  display: flex
  align-items: center
</style>

<script lang="ts">
import { Component, Emit, Inject, Prop, Vue } from 'vue-property-decorator'
import {
  MessageThread,
  RefObjectType,
} from '@/widgets/messages/types/MessageThread'
import { ThreadSubject } from '@/widgets/messages/types/ThreadSubject'
import ThreadMenu from '@/widgets/messages/components/thread/header/ThreadMenu.vue'
import ThreadTitle from '@/widgets/messages/components/thread/header/ThreadTitle.vue'
import ThreadSubjectChip from '@/widgets/messages/components/thread/header/ThreadSubjectChip.vue'
import ThreadManagerAvatars from '@/widgets/messages/components/thread/thread-managers/ThreadManagerAvatars.vue'
import FavoriteToggle from '@/widgets/messages/components/thread/header/FavoriteToggle.vue'
import MessageModule from '@/widgets/messages/modules/MessageModule'

@Component({
  components: {
    FavoriteToggle,
    ThreadManagerAvatars,
    ThreadSubjectChip,
    ThreadTitle,
    ThreadMenu,
  },
})
export default class ThreadHeader extends Vue {
  @Prop({ type: Object, required: true })
  thread!: MessageThread

  @Inject('MessageModule')
  messageModule!: MessageModule

  orderName: string | null = null

  get subjects(): ThreadSubject[] {
    return this.messageModule.subjects
  }

  changeSubject(subject: ThreadSubject) {
    this.orderName = null

    this.messageModule.updateThread({
      ...this.thread,
      subjectId: subject.id,
      refObject: null,
    })

    this.messageModule.changeThreadSubject({
      threadId: this.thread.id,
      subjectId: subject.id,
    })
  }

  changeOrder(orderName: string) {
    this.orderName = orderName

    if (this.orderName) {
      this.messageModule.changeThreadOrder({
        threadId: this.thread.id,
        orderName: this.orderName,
      })
    }
  }

  created() {
    if (!this.thread.refObject) {
      return
    }

    if (this.thread.refObject.type === RefObjectType.order) {
      this.orderName = this.thread.refObject.title
    }
  }

  @Emit()
  showManagers() {
    return true
  }
}
</script>
