<script lang="ts">
import { ref, type Ref } from 'vue'

export default {
  props: {
    isLive: {
      type: Boolean,
      default() {
        return false
      }
    },
    channelName: {
      type: String
    }
  },
  setup(props) {
    let messages: Ref<
      { username: string; channel: string; message: string; messageType: string, tags: Record<string,string> }[]
    > = ref([])
    let ws = new WebSocket('ws://localhost:7000')

    return {
      ws,
      messages,
      props
    }
  },
  mounted() {
    const chatList = this.$refs.chatList as Element
    const chatStatusMessage = this.$refs.initConnectingStatus as Element

    this.ws.onmessage = (message) => {
      if (message.data == 'OK') {
        chatStatusMessage.textContent = `Connected to ${this.channelName}`
      } else {
        this.messages.push(JSON.parse(message.data))
        this.clearMessages()
        this.scrollToBottom(chatList)
      }
    }

    this.ws.onopen = (data) => {
      console.log(data)
      this.ws.send('JOIN ' + this.props.channelName?.toLowerCase())
    }
  },
  methods: {
    getChat() {
      return this.messages
    },
    scrollToBottom(el: Element) {
      el.scrollTop = el.scrollHeight
    },
    clearMessages() {
      if (this.messages.length > 50) {
        this.messages.shift
      }
    }
  }
}
</script>
<template>
  <div v-if="isLive" class="p-3 bg-ctp-crust rounded-lg w-full max-w-[15.625rem] flex flex-col">
    <ul class="overflow-y-scroll  overflow-x-hidden whitespace-pre-wrap h-[46.875rem]" ref="chatList">
      <li>
        <p ref="initConnectingStatus" class="text-gray-500 text-sm italic">
          Connecting to {{ channelName }}.
        </p>
      </li>
      <li v-for="message in getChat()" :key="messages.indexOf(message)">
        <div class="text-white inline-flex">
          <p class="text-sm">
            <strong :style="message.tags.color ? `color: ${message.tags.color};` : ``" class="text-ctp-pink font-bold text-sm">{{ message.username }}</strong
            >: {{ message.message }}
          </p>
        </div>
      </li>
    </ul>
  </div>
</template>
