<template>
  <div class="flex justify-center">
    <div v-if="whisperersUids.length > 0" class="flex no-wrap ui-gap-x-xs">
      <q-chat-message bg-color="white" sent class="q-mr-xs">
        <q-spinner-dots size="2rem" />
      </q-chat-message>
      <ui-user-avatar
        v-for="manager in managers"
        :key="manager.id"
        :user="manager"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Inject, Prop, Vue } from 'vue-property-decorator'
import MessageWebsocketService from '@/widgets/messages/services/MessageWebsocketService'
import { MessageUserModule } from '@/widgets/messages/modules/MessageUserModule'
import { Manager } from '@/types/Manager'
import Timeout = NodeJS.Timeout
import { ManagerModule } from '@/widgets/messages/modules/ManagerModule'
import UiUserAvatar from '@/lib-components/UiUserAvatar.vue'
import { QChatMessage, QSpinnerDots } from 'quasar'

@Component({
  components: { UiUserAvatar, QChatMessage, QSpinnerDots },
})
export default class Whisperers extends Vue {
  @Prop({ type: Number, required: true })
  threadId!: number

  @Inject('MessageUserModule')
  userModule!: MessageUserModule

  @Inject('ManagerModule')
  managerModule!: ManagerModule

  whisperersUids: string[] = []
  timeouts: { [key: string]: Timeout } = {}
  interval: null | Timeout = null

  get managers(): Manager[] {
    return this.managerModule.managersByUids(this.whisperersUids)
  }

  get currentManager(): Manager {
    return this.userModule.user as Manager
  }

  created() {
    MessageWebsocketService.onWhisper(this.threadId, payload => {
      const managerUid = payload.userId

      if (this.currentManager.id === managerUid) {
        return
      }

      if (this.whisperersUids.includes(managerUid)) {
        clearTimeout(this.timeouts[managerUid])
      } else {
        this.whisperersUids.push(managerUid)
      }

      this.timeouts[managerUid] = setTimeout(() => {
        const index = this.whisperersUids.indexOf(managerUid)

        if (index !== -1) {
          this.whisperersUids.splice(index, 1)
        }
      }, 5000)
    })

    this.interval = setInterval(() => {
      const manager = this.userModule.user as Manager

      MessageWebsocketService.whisper(this.threadId, manager.id)
    }, 3000)
  }

  destroyed() {
    if (this.interval) {
      clearInterval(this.interval)
    }

    Object.values(this.timeouts).forEach(timeout => clearTimeout(timeout))
  }
}
</script>

<style scoped lang="sass">
::v-deep
  .q-message-text
    min-height: initial
    padding: 0 8px
</style>
