<template>
  <img alt="" class="bg-img" src="">
  <div class="wrapper">
    <div class="container">
      <div class="card mb-3 bg-transparent border-0">
        <div class="row g-0">
          <div class="img-container col-md-2 pt-3">
            <img
                :class="data.playerDetails.tracked ? 'tracked' : ''" :src="data.playerDetails.avatar"
                :title="data.playerDetails.tracked ? 'Tracked' : ''"
                alt="Player avatar"
                class="img-fluid avatar">
          </div>
          <div class="col-md-8 d-flex">
            <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
                }}
                <i class="fas fa-link"></i>
              </a></h3>
              <table class="table table-borderless text-center">
                <tr>
                  <th class="wlt-win text-uppercase text-muted">Wins</th>
                  <th class="wlt-loss text-uppercase text-muted">Losses</th>
                  <th class="wlt-tie text-uppercase text-muted">Ties</th>
                  <th class="wlt-win-rate text-uppercase text-muted">Win-Rate</th>
                  <th class="wlt-tie-rate text-uppercase text-muted">Tie-Rate</th>
                </tr>
                <tr>
                  <td class="wlt-win">{{ data.match_stats.win }}</td>
                  <td class="wlt-loss">{{ data.match_stats.loss }}</td>
                  <td class="wlt-tie">{{ data.match_stats.tie }}</td>
                  <td class="wlt-win-rate">{{
                      (data.match_stats.win / (data.match_stats.win + data.match_stats.loss + data.match_stats.tie) * 100).toFixed(2)
                    }}%
                  </td>
                  <td class="wlt-tie-rate">{{
                      (data.match_stats.tie / (data.match_stats.win + data.match_stats.loss + data.match_stats.tie) * 100).toFixed(2)
                    }}%
                  </td>
                </tr>
              </table>
            </div>
            <div v-if="!data.playerDetails.tracked" class="dropdown trackme-btn">
              <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 class="matches m-auto">
        <table v-if="data.matches" class="table table-borderless">
          <thead class="border-bottom">
          <tr>
            <th class="text-center map" scope="col">Map</th>
            <th class="text-center rank" scope="col">Rank</th>
            <th class="text-center length" scope="col" title="Match Length">
              <i class="far fa-clock"></i>
            </th>
            <th class="text-center score" scope="col">Score</th>
            <th class="text-center kills" scope="col">K</th>
            <th class="text-center assists" scope="col">A</th>
            <th class="text-center deaths" scope="col">D</th>
            <th class="text-center kdiff" scope="col" style="cursor: help" title="Kill-to-death ratio">+/-</th>
            <th class="text-center hltv" scope="col" style="cursor: help" title="HLTV 1.0 Rating">Rating</th>
            <th class="text-center duration" scope="col">Duration</th>
            <th class="date" scope="col">Date</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="match in data.matches"
              :key="match.match_id"
              :class="GetWinLoss(match.match_result, match.stats[0].team_id)"
              class="match"
              @click="GoToMatch(match.match_id)">
            <td class="td-map text-center">
              <i v-if="match.parsed" class="far fa-chart-bar parsed" style="cursor: help"
                 title="Demo has been parsed for additional data"></i>
              <img :alt="match.map ? match.map : 'Map not found'"
                   :src="match.map !== '' ? require('@/images/map_icons/map_icon_' + match.map + '.svg') : require('../images/map_icons/map_icon_lobby_mapveto.svg')"
                   :title="match.map"
                   class="map-icon">
            </td>
            <td class="td-rank text-center">
              <img
                  :alt="DisplayRank(match.stats[0].extended?.rank?.new)[1]"
                  :src="DisplayRank(match.stats[0].extended?.rank?.new)[0]"
                  :title="DisplayRank(match.stats[0].extended?.rank?.new)[1]"
                  class="rank-icon">
            </td>
            <td class="td-length text-center">
              <i v-if="match.max_rounds === 30 || !match.max_rounds" class="fas fa-circle text-muted"
                 title="Long match"></i>
              <i v-if="match.max_rounds === 16" class="far fa-circle text-muted" title="Short match"></i>
            </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="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 :title="FormatFullDuration(match.duration)" class="td-duration text-center">
              {{ FormatDuration(match.duration) }}

            </td>
            <td :title="FormatFullDate(match.date)" 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 {
  DisplayRank,
  FormatDate,
  FormatDuration,
  FormatFullDate,
  FormatFullDuration,
  GetHLTV_1, GoToLink,
  GoToMatch,
  LoadImage,
  SaveLastVisitedToLocalStorage
} from "../utils";

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

    const data = reactive({
      userData: {
        authcode: '',
        sharecode: ''
      },
      playerDetails: {},
      matches: [],
      statusError: '',
      match_stats: {
        loss: 0,
        win: 0,
        tie: 0,
      }
    })

    // 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(`${process.env.VUE_APP_API_URL}/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(`${process.env.VUE_APP_API_URL}/player/${props.id}`)
          .then((response) => {
            data.playerDetails = response.data
            data.matches = response.data.matches
            data.match_stats.loss = response.data.match_stats.loss ? response.data.match_stats.loss : 0
            data.match_stats.win = response.data.match_stats.win ? response.data.match_stats.win : 0
            data.match_stats.tie = response.data.match_stats.tie ? response.data.match_stats.tie : 0
            store.state.id64 = response.data.steamid64

            LoadImage(data.matches[0].map ? data.matches[0].map : 'random')

            // console.log(response.data)

            let player = {
              'steamid64': response.data.steamid64,
              'name': response.data.name,
              'avatar': response.data.avatar
            }
            SaveLastVisitedToLocalStorage(player)

            document.title = `${response.data.name} | csgoWTF`
          })
          .catch((e) => {
            if (e.response.status === 404) {
              GoToLink('/')
            }
            // console.log(e.response.status, e.response.statusText);
          });
    }

    const GetWinLoss = (matchResult, teamId) => {
      if (matchResult === teamId) {
        return 'win'
      } else if (matchResult === 0) {
        return 'draw'
      } else {
        return 'loss'
      }
    }

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

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

    return {
      data,
      store,
      props,
      GetUser,
      TrackMe,
      GetWinLoss,
      FormatDate,
      FormatFullDate,
      FormatDuration,
      FormatFullDuration,
      GoToMatch,
      GetHLTV_1,
      DisplayRank
    }
  }
}
</script>

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

.wrapper {
  padding-bottom: 1rem;
  background: rgba(0, 0, 0, .7);
  min-width: 100%;
  min-height: 100%;

  .trackme-btn {
    position: absolute;
    right: 0;
    bottom: 0;
  }
}

.card {
  padding-top: 10px;

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

    &.tracked {
      box-shadow: 0 0 20px 5px var(--bs-success);
    }
  }

  .fas, .far {
    font-size: .75rem;
    vertical-align: top;
  }

  table {
    max-width: 500px;

    .wlt-win, .wlt-loss, .wlt-tie {
      text-align: start;
      max-width: 70px;
      margin: 0;
      padding: 0;
    }

    .wlt-tie-rate, .wlt-win-rate {
      text-align: end;
      max-width: 90px;
    }
  }
}

.win {
  background: linear-gradient(90deg, rgba(0, 255, 0, .2) 0%, rgba(0, 255, 0, .1) 5%, rgba(20, 20, 20, .8) 15%, rgba(20, 20, 20, .8) 100%);

  &:hover {
    background: linear-gradient(90deg, rgba(0, 255, 0, .2) 0%, rgba(0, 255, 0, .1) 5%, rgba(30, 30, 30, .9) 15%, rgba(30, 30, 30, .9) 100%);
  }
}

.loss {
  background: linear-gradient(90deg, rgba(255, 0, 0, 0.2) 0%, rgba(255, 0, 0, 0.1) 5%, rgba(20, 20, 20, .8) 15%, rgba(20, 20, 20, .8) 100%);

  &:hover {
    background: linear-gradient(90deg, rgba(255, 0, 0, 0.2) 0%, rgba(255, 0, 0, 0.1) 5%, rgba(30, 30, 30, .9) 15%, rgba(30, 30, 30, .9) 100%);
  }
}

.draw {
  background: linear-gradient(90deg, rgba(255, 255, 0, 0.2) 0%, rgba(255, 255, 0, 0.1) 5%, rgba(20, 20, 20, .8) 15%, rgba(20, 20, 20, .8) 100%);

  &:hover {
    background: linear-gradient(90deg, rgba(255, 255, 0, 0.2) 0%, rgba(255, 255, 0, 0.1) 5%, rgba(30, 30, 30, .9) 15%, rgba(30, 30, 30, .9) 100%);
  }
}

table {
  margin-bottom: 0;

  tr {
    th {
      line-height: 1;
    }

    td {
      line-height: 60px;
      font-size: 1rem;
    }

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

    th[title] {
      text-decoration: underline dotted grey;
    }

    td {
      vertical-align: middle;
    }

    .map {
      padding-left: 3rem;
    }

    .td-map {
      position: relative;
      padding-left: 3rem;
      text-align: left !important;
      width: 50px;

      .parsed {
        position: absolute;
        left: 7px;
        top: 27px;
        color: var(--bs-warning);
        font-size: 1.5rem;
      }

      img {
        width: 60px;
        height: auto;
      }
    }

    .td-rank img {
      width: 70px;
      height: auto;

      .rank-icon {
        height: 35px;
      }
    }

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

    .td-date svg {
      margin-left: -5px;
      margin-right: 5px;
    }
  }

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

    &:last-child {
      border: none;
    }

    &:hover {
      cursor: pointer;
    }
  }
}

@media screen and (max-width: 768px) {
  .win {
    background: linear-gradient(90deg, rgba(0, 255, 0, .2) 0%, rgba(0, 255, 0, .1) 5%, var(--bs-body-bg) 30%, var(--bs-body-bg) 100%);
  }

  .loss {
    background: linear-gradient(90deg, rgba(255, 0, 0, 0.2) 0%, rgba(255, 0, 0, 0.1) 5%, var(--bs-body-bg) 30%, var(--bs-body-bg) 100%);
  }

  .draw {
    background: linear-gradient(90deg, rgba(255, 255, 0, 0.2) 0%, rgba(255, 255, 0, 0.1) 5%, var(--bs-body-bg) 30%, var(--bs-body-bg) 100%);
  }
  .card {
    .avatar {
      height: 75px;
      width: 75px;
    }
  }
  .trackme-btn {
    top: 25px;
  }

  .map {
    padding-left: 2.2rem !important;
  }

  .td-map {
    position: relative;
    padding-left: 2.2rem !important;
    width: 35px !important;

    .parsed {
      position: absolute;
      left: .3rem !important;
    }

    img {
      width: 40px !important;
      height: auto;
    }
  }
  .td-rank img {
    width: 50px !important;
    height: auto;
    max-width: 50px;
  }

  .td-score {
    font-size: 1rem !important;
    max-width: 90px;
  }

  .td-date {
    font-size: 1rem !important;
  }

  .kills, .deaths, .assists, .kdiff, .duration, .hltv, .length,
  .td-kills, .td-deaths, .td-assists, .td-plus, .td-duration, .td-hltv, .td-length {
    display: none;
  }
}
</style>