<template>
  <div class="container w-50">
    <TranslateChatButton
        v-if="data.chat.length > 0"
        :translated="data.translatedText.length > 0"
        class="translate-btn"
        @translated="handleTranslatedText"
    />
    <div v-if="data.chat.length > 0" class="chat-history mt-2">
      <table id="chat" :style="`max-width: ${data.clientWidth}px; width: ${data.clientWidth}px`" class="table table-borderless">
        <tbody>
        <tr v-for="(m, id) in data.chat" :key="id">
          <td class="td-time">
            {{ ConvertTickToTime(m.tick, m.tick_rate) }}
          </td>
          <td class="td-avatar">
            <img :class="'team-color-' + m.color"
                 :src="constructAvatarUrl(m.avatar)"
                 alt="Player avatar"
                 class="avatar">
          </td>
          <td :class="m.startSide === 1 ? 'text-info' : 'text-warning'"
              class="td-name d-flex"
              @click="GoToPlayer(m.steamid64)">
          <span>
            <i v-if="m.tracked" class="fa fa-dot-circle-o text-success tracked" title="Tracked user"/>
            <span :class="(m.vac && FormatVacDate(m.vac_date, store.state.matchDetails.date) !== '')
                            || (!m.vac && m.game_ban && FormatVacDate(m.game_ban_date, store.state.matchDetails.date) !== '')
                            ? 'ban-shadow'
                            : ''"
                  :title="!m.vac && m.game_ban
                            ? 'Game-banned: ' + FormatVacDate(m.game_ban_date, store.state.matchDetails.date)
                            : m.vac && !m.game_ban
                            ? 'Vac-banned: ' + FormatVacDate(m.vac_date, store.state.matchDetails.date)
                            : ''">
              {{ m.player }}
            </span>
          </span>
          </td>
          <td class="td-icon">
            <i class="fa fa-caret-right"/>
            <span v-if="!m.all_chat" class="ms-1">
            (team)
          </span>
          </td>
          <td class="td-message">
            {{ data.translatedText.length === 0 ? m.message : data.originalChat[id].message }}
            <span v-if="m.translated_from"
                  :class="m.translated_from ? 'text-success' : ''"
                  :title="`Translated from ${ISO6391.getName(m.translated_from)}`"
                  class="ms-2 helpicon">
            <br/>
            {{ m.message }}
          </span>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
    <div v-else>
      <h3>No chat available</h3>
    </div>
  </div>
</template>

<script>
import {useStore} from "vuex";
import {onMounted, reactive} from "vue";
import {constructAvatarUrl, ConvertTickToTime, FormatVacDate, GetChatHistory, GoToPlayer, truncate} from "@/utils";
import TranslateChatButton from "@/components/TranslateChatButton";
import ISO6391 from 'iso-639-1'

export default {
  name: "MatchChatHistory",
  components: {TranslateChatButton},
  setup() {
    const store = useStore()

    const data = reactive({
      chat: [],
      translatedText: [],
      originalChat: [],
      clientWidth: 0
    })

    const handleTranslatedText = async (e) => {
      const [res, toggle] = await e

      if (res !== null) {
        if (toggle === 'translated') {
          data.translatedText = await setPlayer(sortChatHistory(res, true))
          data.chat = data.translatedText
        } else if (toggle === 'original') {
          data.chat = data.originalChat
        }
      }
    }

    const getChatHistory = async () => {
      const resData = await GetChatHistory(store, store.state.matchDetails.match_id)
      if (resData !== null) {
        data.chat = await setPlayer(sortChatHistory(resData))
        data.originalChat = data.chat
      }
    }

    const sortChatHistory = (res = {}, translated = false) => {
      let arr = []
      if (res !== {}) {
        Object.keys(res).forEach(i => {
          res[i].forEach(o => {
            let obj = Object.assign({
              player: i,
              tick: o.tick,
              all_chat: o.all_chat,
              message: o.message,
              translated_from: translated ? o.translated_from : null,
              translated_to: translated ? o.translated_to : null
            })
            arr.push(obj)
          })
        })
      }
      arr.sort((a, b) => a.tick - b.tick)
      return arr
    }

    const setPlayer = async (chat) => {
      let arr = []
      for (const o of chat) {
        for (const p of store.state.matchDetails.stats) {
          if (o.player === p.player.steamid64) {
            const obj = Object.assign({
              player: truncate(p.player.name, 20),
              steamid64: p.player.steamid64,
              avatar: p.player.avatar,
              color: p.color,
              startSide: p.team_id,
              tracked: p.player.tracked,
              vac: p.player.vac,
              vac_date: p.player.vac_date,
              game_ban: p.player.game_ban,
              game_ban_date: p.player.game_ban_date,
              tick: o.tick,
              tick_rate: store.state.matchDetails.tick_rate && store.state.matchDetails.tick_rate !== -1 ? store.state.matchDetails.tick_rate : 64,
              all_chat: o.all_chat,
              message: o.message,
              translated_from: o.translated_from,
              translated_to: o.translated_to
            })
            arr.push(obj)
          }
        }
      }
      return arr
    }

    const sizeTable = () => {
      if (document.documentElement.clientWidth <= 768) {
        data.clientWidth = document.documentElement.clientWidth - 32
      } else {
        data.clientWidth = 700
      }
    }

    window.onresize = () => {
      sizeTable()
    }

    onMounted(() => {
      getChatHistory()
      sizeTable()
    })

    return {
      data,
      store,
      ISO6391,
      constructAvatarUrl,
      GoToPlayer,
      ConvertTickToTime,
      FormatVacDate,
      handleTranslatedText
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.translate-btn {
  margin-top: .5rem;
}

td {
  padding: .5rem;
}

.td-time {
  width: 80px;
}

.td-avatar {
  width: 30px;

  .avatar {
    width: 20px;
    height: 20px;
    border-radius: 50%;
  }
}

.td-name {
  width: 200px;
  max-width: 200px;
  cursor: pointer;
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

  .tracked {
    font-size: .8rem;
    margin-right: .2rem;
  }

  .ban-shadow {
    color: red;
    text-shadow: 0 0 1rem orangered;
  }
}

.td-icon {
  width: 20px;

  .fa-caret-right {
    font-size: 1rem;
  }
}

.td-message {
  width: 400px !important;
}

@media screen and (max-width: 768px) {
  .container {
    justify-content: flex-start;
    align-items: flex-start;
    margin-left: 1rem;
  }
  .td-name {
    width: 120px !important;
    max-width: 120px !important;
  }
  .td-message {
    width: auto !important;
  }
}

@media screen and (max-width: 576px) {
  .container {
    margin-left: 0;
  }
  .td-avatar {
    display: none;
  }
}
</style>
