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

import BadgeVue from './ChatBadge.vue'
import { parseRawMessage } from '@/assets/messageParser'
import { getEndpoint } from '@/mixins'

import type { Badge, Message } from '@/assets/types'

export default {
  props: {
    channelName: {
      type: String
    }
  },
  async setup(props) {
    const messages = ref<Message[]>([])
    let badges: Badge[] = []
    const wsLink = inject('wsLink') as string

    await getEndpoint(`api/badges?channelName=${props.channelName}`).then((data) => {
      console.log(data)
      badges = data
    })

    return {
      ws: new WebSocket(wsLink),
      messages,
      badges,
      fetchingMoreComments: false
    }
  },
  async mounted() {
    const chatStatusMessage = this.$refs.initConnectingStatus as Element
    this.ws!.onmessage = (message) => {
      if (message.data == 'OK') {
        chatStatusMessage.textContent = this.$t('chat.connected', { username: this.channelName })
      } else {
        this.messages.push(parseRawMessage(message.data, this.badges))
        this.clearMessages()
        this.scrollToBottom()
      }
    }

    this.ws!.onopen = () => {
      this.ws!.send('JOIN ' + this.$props.channelName?.toLowerCase())
    }

    /*    
    await getEndpoint(`api/chat/${this.$props.channelName}/history`).then((data) => {
      this.messages = parseChatHistory(data, this.badges)
    })
      */
  },
  beforeUnmount() {
    this.ws.close()
  },
  methods: {
    getChat() {
      return this.messages
    },
    scrollToBottom() {
      const el = this.$refs.chatList as Element
      el.scrollTop = el.scrollHeight
    },
    clearMessages() {
      if (this.messages.length > 50) {
        this.messages.splice(0, this.messages.length - 50)
      }
    }
  },
  components: {
    BadgeVue
  },
  unmounted() {
    this.messages = []
    this.badges = []
  }
}
</script>
<template>
  <div class="p-3 bg-crust rounded-lg w-[99vw] md:max-w-[15.625rem] lg:max-w-[20rem] flex flex-col">
    <!-- SYSTEM MESSAGES -->
    <ul
      class="overflow-y-scroll overflow-x-hidden space-y-1 whitespace-pre-wrap h-[46.875rem]"
      ref="chatList"
    >
      <li>
        <p ref="initConnectingStatus" class="text-gray-500 text-sm italic">
          {{ $t('chat.connecting', { username: channelName }) }}
        </p>
      </li>
      <li v-for="message in getChat()" :key="messages.indexOf(message)">
        <div v-if="message.type === 'PRIVMSG'" class="text-contrast inline-flex">
          <!-- CHAT MESSAGE-->
          <div class="text-sm items-center">
            <ul v-if="message.tags.badges.length > 0" class="inline-flex space-x-1 pr-1">
              <li v-for="badge in message.tags.badges" :key="badge.id">
                <badge-vue :badge-info="badge"></badge-vue>
              </li>
            </ul>

            <p class="inline">
              <strong
                :style="message.tags.color ? `color: ${message.tags.color};` : ``"
                class="text-purple font-bold"
              >
                {{ message.username }}</strong
              >: {{ message.message }}
            </p>
          </div>
        </div>

        <!--
        
        <div v-else-if="message.type === 'CLEARMSG'" class="text-contrast inline-flex">
          <p class="text-sm text-gray-500 italic">
            {{ $t('chat.removed', { username: message.username }) }}
          </p>
        </div>
        -->

        <div
          v-else-if="message.type === 'USERNOTICE'"
          class="text-contrast inline-flex bg-pink bg-opacity-50 p-1 rounded-md"
        >
          <p>
            {{
              $t('chat.resub', {
                username: message.username,
                duration: message.tags['msg-param-months']
              })
            }}
          </p>
        </div>

        <div
          v-else-if="message.type === 'CLEARCHAT'"
          class="text-contrast inline-flex p-1 rounded-md"
        >
          <p v-if="!message.tags['@ban-duration']" class="text-sm text-gray-500 italic">
            {{ $t('chat.banned', { username: message.message }) }}
          </p>
          <p v-else class="text-sm text-gray-500 italic">
            {{
              $t('chat.timeout', {
                username: message.message,
                duration: message.tags['@ban-duration']
              })
            }}
          </p>
        </div>

        <!--
        <div
          v-else-if="message.type === 'NOTICE'"
          class="text-contrast inline-flex bg-pink bg-opacity-50 p-1 rounded-md"
        >
          <p>{{ message.data.message }}</p>
        </div>

        <div v-else class="text-contrast">
          {{ message }}
        </div>
        -->
      </li>
    </ul>
  </div>
</template>
