<template>
  <img alt="" class="bg-img" src="">

  <div class="">
    <div class="head row m-auto text-center">
      <div class="m-auto map">
        <img v-if="data.matchDetails.map" :alt="data.matchDetails.map"
             :src="require('@/images/map_icons/map_icon_' + data.matchDetails.map + '.svg')"
             :title="data.matchDetails.map" class="map-icon">
        <img v-if="!data.matchDetails.map" :src="require('../images/map_icons/map_icon_lobby_mapveto.svg')"
             alt="Map icon"
             class="map-icon" title="Map unknown">
      </div>
      <p class="text-center text-muted fs-6">
        {{ FormatFullDate(data.matchDetails.date) }}
      </p>
      <p class="text-center fs-6">
        <span class="text-muted">Match Length:</span> {{ data.matchDetails.max_rounds === 16 ? 'Short' : 'Long' }}
        <svg class="bi bi-circle-fill mx-2" fill="currentColor" height="8" viewBox="0 0 16 16" width="8"
             xmlns="http://www.w3.org/2000/svg">
          <circle cx="8" cy="8" r="8"/>
        </svg>
        <span class="text-muted">Average Rank:</span> <img
          :alt="DisplayRank(data.avgRank)[1]"
          :src="DisplayRank(data.avgRank)[0]"
          :title="DisplayRank(data.avgRank)[1]"
          class="rank-icon"/>
      </p>
    </div>
  </div>
  <div class="nav navbar-dark navbar-expand-lg">
    <button aria-controls="matchNav" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler"
            data-bs-target="#matchNav" data-bs-toggle="collapse" type="button">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div id="matchNav" class="collapse navbar-collapse">
      <ul class="list-unstyled d-flex m-auto">
        <li class="list-item scoreboard active" @click.prevent="ActivateScoreInfo('scoreboard')">Scoreboard</li>
        <li :class="!data.matchDetails.parsed ? 'disabled' : ''" class="list-item flashes"
            @click.prevent="data.matchDetails.parsed ? ActivateScoreInfo('flashes') : null" :title="!data.matchDetails.parsed ? 'This demo has not been parsed' : ''">Flashes
        </li>
        <li :class="!data.matchDetails.parsed ? 'disabled' : ''" class="list-item utility"
            @click.prevent="data.matchDetails.parsed ? ActivateScoreInfo('utility') : null" :title="!data.matchDetails.parsed ? 'This demo has not been parsed' : ''">Utility
        </li>
        <li :class="!data.matchDetails.parsed ? 'disabled' : ''" class="list-item damage"
            @click.prevent="data.matchDetails.parsed ? ActivateScoreInfo('damage') : null" :title="!data.matchDetails.parsed ? 'This demo has not been parsed' : ''">Damage
        </li>
      </ul>
    </div>
  </div>
  <div v-if="data.score.length === 2 && data.stats" id="scoreWrapper" class="scoreboard">
    <div id="scoreboard" class="active">
      <ScoreTeam
          :rounds="data.matchDetails.max_rounds ? data.matchDetails.max_rounds : data.score[data.matchDetails.match_result - 1] === 16 ? 30 : data.score[data.matchDetails.match_result - 1] === 15 ? 30 : 16"
          :rounds_played="data.score.reduce((a, b) => a + b)"
          :score="data.score[0]"
          :stats="data.stats" :team_id="1" :parsed="data.matchDetails.parsed" />
      <ScoreTeam
          :rounds="data.matchDetails.max_rounds ? data.matchDetails.max_rounds : data.score.reduce((a, b) => a + b) >= 16 ? 30 : 16"
          :rounds_played="data.score.reduce((a, b) => a + b)"
          :score="data.score[1]"
          :stats="data.stats" :team_id="2" :parsed="data.matchDetails.parsed" />
    </div>

    <div id="flashes">
      <FlashChart v-for="(player, id) in data.stats" :id="id"
                  :key="player.player.steamid64"
                  :avatar="player.player.avatar"
                  :duration="player.extended.flash.duration"
                  :name="player.player.name"
                  :total="player.extended.flash.total"
      />
    </div>

    <div id="utility">
      <UtilityChartTotal :stats="data.stats"/>
      <UtilityChart v-for="(player, id) in data.stats" :id="id"
                    :key="player.player.steamid64"
                    :avatar="player.player.avatar"
                    :name="player.player.name"
                    :ud="player.extended.dmg.ud"
      />
    </div>

    <div id="damage">
      <DamageChart :stats="data.stats" />
    </div>
  </div>
</template>

<script>
import {defineAsyncComponent, onBeforeMount, onMounted, reactive, watch} from "vue";
import axios from 'axios'
import {DisplayRank, FormatFullDate, GetHLTV_1, GoToPlayer, LoadImage} from "../utils";
import router from "../router";

const ScoreTeam = defineAsyncComponent(() => import('../components/ScoreTeam'))
const FlashChart = defineAsyncComponent(() => import('../components/FlashChart'))
const UtilityChart = defineAsyncComponent(() => import('../components/UtilityChart'))
const UtilityChartTotal = defineAsyncComponent(() => import('../components/UtilityChartTotal'))
const DamageChart = defineAsyncComponent(() => import('../components/DamageChart'))

export default {
  name: 'Match',
  props: ['match_id'],
  components: {
    ScoreTeam,
    FlashChart,
    UtilityChart,
    UtilityChartTotal,
    DamageChart
  },
  setup(props) {
    // Refs
    const data = reactive({
      playerName: '',
      matchDetails: {},
      stats: [],
      score: [0],
      avgRank: 0,
    })

    // Functions
    const GetMatch = () => {
      axios
          .get(`${process.env.VUE_APP_API_URL}/match/${props.match_id}`)
          .then((response) => {
            document.title = `${response.data.map} | csgoWTF`
            data.matchDetails = response.data
            data.stats = response.data.stats
            data.score = response.data.score

            LoadImage(data.matchDetails.map ? data.matchDetails.map : 'random')

            console.log(response.data)
          })
          .catch((e) => {
            console.log(e)
          })
    }

    const GetAvgRank = () => {
      let count = 0
      let fullRank = 0

      data.stats?.map(player => {
        if (player.extended?.rank?.old) {
          fullRank += player.extended?.rank?.old
          count += 1
        }
      })

      if (count === 0)
        data.avgRank = 0
      else
        data.avgRank = Math.floor(fullRank / count)
    }

    const ActivateScoreInfo = (id) => {
      const activeNavItems = document.querySelector('#matchNav').querySelectorAll('.active')
      const newNavItem = document.querySelector(`#matchNav .${id}`)
      const activeItems = document.querySelector('#scoreWrapper').querySelectorAll('.active')
      const newItem = document.querySelector(`#scoreWrapper #${id}`)

      activeNavItems.forEach(item => item.classList.remove('active'))
      activeItems.forEach(item => item.classList.remove('active'))

      newNavItem.classList.add('active')
      newItem.classList.add('active')

      if (id === 'flashes' || id === 'utility' || id === 'damage') {
        history.replaceState({}, null, `/match/${data.matchDetails.match_id}/${id}`)
      } else if (id === 'scoreboard') {
        history.replaceState({}, null, `/match/${data.matchDetails.match_id}`)
      }
    }

    // Watchers
    watch(() => props.match_id, GetMatch)
    watch(() => data.stats, GetAvgRank)

    // Run on create
    onBeforeMount(() => {
      GetMatch()
    })

    onMounted(() => {
      setTimeout(() => {
        if (router.currentRoute.value.href.split('/')[3]) {
          ActivateScoreInfo(router.currentRoute.value.href.split('/')[3])
        }
      }, 200)
    })

    return {
      GetMatch, GetAvgRank, ActivateScoreInfo, data, GoToPlayer, GetHLTV_1, DisplayRank, FormatFullDate, LoadImage
    }
  }
}
</script>

<style lang="scss" scoped>
.bg-img {
  z-index: -1;
  position: fixed;
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 100%;
}

.head {
  background: linear-gradient(90deg,
      rgba(0, 0, 0, 0.7) 0%,
      rgba(0, 0, 0, 0.95) 30%,
      rgba(0, 0, 0, 0.95) 70%,
      rgba(0, 0, 0, .7) 100%
  );

  .map img {
    width: auto;
    height: 100px;
    margin: 10px 0;
  }

  .rank-icon {
    width: 60px;
  }
}

#scoreWrapper {
  z-index: 1;
  height: 100%;
  width: 100%;
  max-width: 100vw;
  background: linear-gradient(90deg,
      rgba(0, 0, 0, 0.6) 0%,
      rgba(0, 0, 0, 0.85) 30%,
      rgba(0, 0, 0, 0.85) 70%,
      rgba(0, 0, 0, .6) 100%
  );

  #scoreboard, #flashes, #utility, #damage {
    display: none;
    flex-direction: column;
    align-items: center;
  }

  #scoreboard.active,
  #flashes.active,
  #utility.active,
  #damage.active {
    display: flex;
  }
}

.nav {
  max-width: 100vw;
  background: rgba(0, 0, 0, 0.9);
  background: linear-gradient(90deg,
      rgba(0, 0, 0, 0.7) 0%,
      rgba(0, 0, 0, 0.95) 30%,
      rgba(0, 0, 0, 0.95) 70%,
      rgba(0, 0, 0, .7) 100%
  );
  border-top: 1px solid rgba(255, 255, 255, .2);
  border-bottom: 1px solid rgba(255, 255, 255, .2);

  .list-item {
    padding: 10px 10px;

    &:hover {
      background: var(--bs-info);
      cursor: pointer;
    }
  }

  .active {
    background: var(--bs-info)
  }

  .disabled {
    color: #585858;

    &:hover {
      background: transparent;
      cursor: default;
    }
  }
}
</style>
