<template>
  <div class="chat-block-container">
    <div class="chats-list">
      <template v-for="(chat, index) in chats" :key="chat.id">
        <ChatElement
          :chat.sync="chats[index]"
          :user-id="userId"
          :otherUser="otherUserName(chats[index].id)"
          :activeChat="chat.id == activeChat.id"
          @chat:select="setActiveChat"
        />
      </template>
    </div>
    <div class="messages-container">
      <h3 class="p-2">{{ otherUserName(activeChat.id) }}</h3>
      <div class="messages-list">
        <template v-for="(message, index) in messages" :key="message.id">
          <Message :message.sync="messages[index]" :user-id="userId"/>
        </template>
      </div>
      <div class="add-message-container">
        <textarea id="messageInput"
                  class="form-control"
                  @keyup.enter.exact="addMessage"
                  v-model="newMessage"></textarea>
        
        <div class="message-buttons">
          <button @click="addMessage" class="btn btn-primary send-button" disabled>
            <i class="bi bi-send m-0 me-1"></i>
            Send
          </button>
        </div>
        
      </div>
    </div>
  </div>
</template>

<script>
  import Message from './message.vue';
  import ChatElement from './chat_element.vue';
  
  export default {
    name: 'ChatContainer',
    components: { Message, ChatElement, Attachment, Document },
    data() {
      return {
        chatId: $('#chatContainer').data('chat-id'),
        userId: $('#chatContainer').data('user-id'),
    },
    created() {
      $.get(this.chatsUrl, (result) => {
        this.chats = result
        this.setActiveChat(this.chatId)
      });

      let container = this;
      consumer.subscriptions.create(
        { channel: "UserChatsChannel", user: $('#chatContainer').data('user-id') },
        { received(data) {
          let chatPosition = container.chats.findIndex(e => e.id == data.id)
          if ( chatPosition >= 0 ) {
            container.chats[chatPosition].last_message = data.last_message
            container.chats[chatPosition].updated_at = data.updated_at
          } else {
            container.chats.push(data)
          }
          container.reorderChats()
        }}
      )
    },
  }
  ... more code ...
</script>