<template>
  <div class="thread-messages">
    <template v-if="!!previewMessages && hideMessages">
      <message
        @set-edit="setEdit"
        v-for="message in previewMessages.first"
        :key="message.id"
        :message="message"
        :thread="thread"
        :client="thread.client"
      />
      <div class="flex justify-center">
        <q-btn
          @click="hideMessages = false"
          flat
          rounded
          color="primary"
          :label="showAllMessagesLabel"
        />
      </div>
      <message
        @set-edit="setEdit"
        v-for="message in previewMessages.last"
        :key="message.id"
        :message="message"
        :client="thread.client"
      />
    </template>
    <template v-else>
      <message
        v-for="message in thread.messages"
        @set-edit="setEdit"
        :message="message"
        :client="thread.client"
        :key="message.id"
      />
    </template>
  </div>
</template>

<style lang="sass" scoped>
.thread-messages
  padding: 0 8px

  & > *
    margin-bottom: 8px
</style>

<script lang="ts">
import { Component, Emit, Prop, Vue } from 'vue-property-decorator'
import { getModule } from 'vuex-module-decorators'
import { MessageThread } from '@/widgets/messages/types/MessageThread'
import { PreviewMessages } from '@/widgets/messages/types/PreviewMessages'
import MessageModule from '@/widgets/messages/modules/MessageModule'
import Message from '@/widgets/messages/components/message/Message.vue'
import { QBtn } from 'quasar'

@Component({
  components: { Message, QBtn },
})
export default class ThreadMessages extends Vue {
  @Prop({ type: Object, required: true })
  thread!: MessageThread

  @Prop({ type: Boolean, default: true })
  dense!: boolean

  messageModule!: MessageModule
  hideMessages = this.dense

  get previewMessages(): PreviewMessages | null {
    return this.messageModule.getPreviewMessages(this.thread)
  }

  get countHiddenMessage(): number {
    if (!this.previewMessages) {
      return 0
    }

    return (
      this.thread.messages.length -
      this.previewMessages.first.length -
      this.previewMessages.last.length
    )
  }

  get showAllMessagesLabel(): string {
    return `Загрузить ${this.countHiddenMessage} сообщений`
  }

  created() {
    this.messageModule = getModule(MessageModule, this.$store)
  }

  @Emit()
  setEdit(isEdit: boolean) {
    return isEdit
  }
}
</script>
