<template>
  <div class="wrapper">
    <div class="container">
      <div class="card mb-3 bg-transparent border-0" style="max-width: 540px;">
        <div class="row g-0">
          <div class="img-container col-md-4 pt-3">
            <img
                :src="data.playerDetails.avatar" alt="Player avatar" class="img-fluid avatar">
          </div>
          <div class="col-md-8">
            <div class="card-body">
              <h3 class="card-title"><a
                  :href="/^\d{17}$/.test(props.id) ? 'https://steamcommunity.com/profiles/' + props.id : 'https://steamcommunity.com/id/' + props.id"
                  class="text-decoration-none text-white"
                  target="_blank"
                  title="Open steam profile">{{
                  data.playerDetails.name
                }}
                <svg class="bi bi-link-45deg" fill="currentColor" height="16" viewBox="0 0 16 16"
                     width="16" xmlns="http://www.w3.org/2000/svg">
                  <path
                      d="M4.715 6.542 3.343 7.914a3 3 0 1 0 4.243 4.243l1.828-1.829A3 3 0 0 0 8.586 5.5L8 6.086a1.002 1.002 0 0 0-.154.199 2 2 0 0 1 .861 3.337L6.88 11.45a2 2 0 1 1-2.83-2.83l.793-.792a4.018 4.018 0 0 1-.128-1.287z"/>
                  <path
                      d="M6.586 4.672A3 3 0 0 0 7.414 9.5l.775-.776a2 2 0 0 1-.896-3.346L9.12 3.55a2 2 0 1 1 2.83 2.83l-.793.792c.112.42.155.855.128 1.287l1.372-1.372a3 3 0 1 0-4.243-4.243L6.586 4.672z"/>
                </svg>
              </a></h3>
              <table class="table table-borderless">
                <tr>
                  <th class="text-uppercase text-muted">Wins</th>
                  <th class="text-uppercase text-muted">Losses</th>
                  <th class="text-uppercase text-muted">WinRate</th>
                </tr>
                <tr>
                  <td>{{ wl.win }}</td>
                  <td>{{ wl.loss }}</td>
                  <td>{{ (wl.win / wl.loss * 100).toFixed(2) }}%</td>
                </tr>
              </table>
              <small v-if="data.playerDetails.tracked" class="card-text text-muted">
                Currently tracked
              </small>
              <div v-else class="dropdown">
                <button
                    id="login-dropdown"
                    aria-expanded="false"
                    class="btn border-2 btn-outline-info"
                    data-bs-toggle="dropdown"
                    type="button"
                >
                  Track Me!
                </button>
                <div aria-labelledby="login-dropdown" class="dropdown-menu mt-2 border-2 border-primary bg-body"
                     style="width: 320px">
                  <form class="px-4 py-3">
                    <!-- AuthCode input -->
                    <div class="form-outline mb-4">
                      <input id="track-authcode" v-model="data.userData.authcode" class="form-control bg-secondary"
                             placeholder="AuthCode*"
                             required type="text"/>
                    </div>

                    <!-- ShareCode input -->
                    <div class="form-outline mb-2">
                      <input id="track-sharecode" v-model="data.userData.sharecode" class="form-control bg-secondary"
                             placeholder="ShareCode"
                             type="text"/>
                    </div>

                    <div class="form-outline mb-4">
                      <small>You can find your AuthCode and ShareCode <a
                          href="https://help.steampowered.com/en/wizard/HelpWithGameIssue/?appid=730&issueid=128" target="_blank">here</a>.</small>
                    </div>

                    <!-- Submit button -->
                    <button class="btn btn-outline-warning border-2" type="submit" @click.prevent="TrackMe">
                      TrackMe
                    </button>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="matches m-auto">
        <table v-if="data.matches" class="table table-borderless">
          <thead class="border-bottom">
          <tr>
            <th class="text-center" scope="col">Map</th>
            <th class="text-center" scope="col">Rank</th>
            <th class="text-center" scope="col">Score</th>
            <th class="text-center" scope="col">K</th>
            <th class="text-center" scope="col">A</th>
            <th class="text-center" scope="col">D</th>
            <th class="text-center" scope="col" style="cursor: help" title="Kill-to-death ratio">+/-</th>
            <th class="text-center" scope="col" style="cursor: help" title="Average damage per round">ADR</th>
            <th class="text-center" scope="col" style="cursor: help" title="HLTV 1.0 Rating">Rating</th>
            <th class="text-center" scope="col">Duration</th>
            <th scope="col">Date</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="match in data.matches"
              :key="match.match_id"
              class="match"
              @click="GoToMatch(match.match_id)">
            <td class="td-map text-center">
              <img :alt="match.map ? match.map : 'Map not found'"
                   :src="mapImg.includes(match.map) ? require('@/images/maps/' + match.map + '.png') : require('@/images/maps/not_found.png')"
                   :title="match.map"
                   class="map-icon">
            </td>
            <td class="td-rank text-center">
              <img
                  :src="match.stats[0].extended?.rank?.new ? require('@/images/ranks/' + match.stats[0].extended?.rank?.new + '.png') : require('@/images/ranks/0.png')"
                  alt="Rank icon"
                  class="rank-icon">
            </td>
            <td :class="match.stats[0].team_id === match.match_result ? 'text-success' : !match.match_result ? 'text-warning' : 'text-danger'"
                class="td-score text-center fw-bold">
              {{ match.score[0] }} - {{ match.score[1] }}
            </td>
            <td class="td-kills text-center">
              {{ match.stats[0].kills ? match.stats[0].kills : "0" }}
            </td>
            <td class="td-assists text-center">
              {{ match.stats[0].assists ? match.stats[0].assists : "0" }}
            </td>
            <td class="td-deaths text-center">
              {{ match.stats[0].deaths ? match.stats[0].deaths : "0" }}
            </td>
            <td :class="(match.stats[0].kills ? match.stats[0].kills : 0) - (match.stats[0].deaths ? match.stats[0].deaths : 0) >= 0 ? 'text-success' : 'text-danger'"
                class="td-plus text-center">
              {{
                (match.stats[0].kills ? match.stats[0].kills : 0) - (match.stats[0].deaths ? match.stats[0].deaths : 0)
              }}
            </td>
            <td class="td-adr text-center">
              {{
                Math.floor((match.stats[0].extended.dmg.total ? match.stats[0].extended.dmg.total : 0) / (match.score[0] + match.score[1]))
              }}
            </td>
            <td :class="GetHLTV_1(
                      match.stats[0].kills,
                      match.score[0] + match.score[1],
                      match.stats[0].deaths,
                      match.stats[0].extended?.multi_kills?.duo,
                      match.stats[0].extended?.multi_kills?.triple,
                      match.stats[0].extended?.multi_kills?.quad,
                      match.stats[0].extended?.multi_kills?.pent) >= 1 ? 'text-success' : 'text-warning'"
                class="td-hltv text-center fw-bold">
              {{
                GetHLTV_1(
                    match.stats[0].kills,
                    match.score[0] + match.score[1],
                    match.stats[0].deaths,
                    match.stats[0].extended?.multi_kills?.duo,
                    match.stats[0].extended?.multi_kills?.triple,
                    match.stats[0].extended?.multi_kills?.quad,
                    match.stats[0].extended?.multi_kills?.pent)
              }}
            </td>
            <td class="td-duration text-center">
              {{ FormatDuration(match.duration) }}
            </td>
            <td class="td-date">
              {{ FormatDate(match.date) }}
            </td>
          </tr>
          </tbody>
        </table>
        <h5 v-else>No matches on record</h5>
      </div>
    </div>
  </div>
</template>

<script>
import {onBeforeMount, reactive, watch} from "vue";
import axios from "axios";
import {useStore} from "vuex";
import {FormatDate, FormatDuration, GetHLTV_1, GoToMatch} from "@/utils";

export default {
  name: 'Player',
  props: ['id'],
  setup(props) {
    const store = useStore()

    // Vars
    const mapImg = ['de_inferno', 'de_mirage', 'de_overpass']

    const wl = reactive({
      win: 132,
      loss: 102
    })

    const data = reactive({
      userData: {
        authcode: '',
        sharecode: ''
      },
      playerDetails: {},
      matches: [],
      statusError: ''
    })

    // Functions
    const TrackMe = async () => {
      const shareCodeRegex = /^CSGO(?:-?[ABCDEFGHJKLMNOPQRSTUVWXYZabcdefhijkmnopqrstuvwxyz23456789]{5}){5}$/
      const authCodeRegex = /^[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{4}-[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{5}-[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{4}$/

      if (!shareCodeRegex.test(data.userData.sharecode))
        data.statusError = 'Is not a valid sharecode'
      if (!authCodeRegex.test(data.userData.authcode))
        data.statusError = 'Is not a valid authcode'

      const res = await axios
          .post(`http://localhost:1337/http://localhost:8000/player/trackme`, `id=${store.state.id64}&authcode=${data.userData.authcode}&sharecode=${data.userData.sharecode}`)

      if (res.status === 401) {
        data.statusError = 'Data does not match player'
      } else if (res.status === 400) {
        data.statusError = 'Userinput was wrong'
      } else if (res.status === 200) {
        data.statusError = ''
      } else {
        console.log(`${res.status}: ${res.statusText}`)
      }
    }

    const GetUser = () => {
      axios
          .get(`http://localhost:1337/http://localhost:8000/player/${props.id}`)
          .then((response) => {
            data.playerDetails = response.data
            data.matches = response.data.matches
            store.state.id64 = response.data.steamid64

            console.log(response.data)
            document.title = `${response.data.name} | CSGO-W.TF`
          })
          .catch((e) => {
            console.log(e);
          });
    }

    watch(() => props.id, GetUser)

    onBeforeMount(() => {
      GetUser()
    })

    return {
      data, store, mapImg, wl, props, GetUser, TrackMe, FormatDate, FormatDuration, GoToMatch, GetHLTV_1
    }
  }
}
</script>

<style lang="scss" scoped>
.card {
  padding-top: 10px;
}

td {
  vertical-align: middle;
}

th:last-child, td:last-child {
  text-align: right;
  width: 150px;
}

.td-map {
  width: 100px;
  height: 100px;
}

.td-rank {
  width: 88px;
  height: 35px;
}

.td-score {
  font-size: 1.2rem;
  width: 120px;
}

.avatar {
  border-radius: 50%;
  height: 150px;
  width: 150px;
  box-shadow: 0 0 10px black;
}

.map-icon {
  height: 75px;
}

.rank-icon {
  height: 35px;
}

.match {
  border-bottom: 1px solid rgba(73, 73, 73, 0.73);
}

.match:last-child {
  border: none;
}

.match:hover {
  cursor: pointer;
  background: rgba(0, 0, 0, 0.25);
}
</style>