<template>
  <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.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 map" scope="col">Map</th>
          <th class="text-center rank" scope="col">Rank</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 adr" scope="col" style="cursor: help" title="Average damage per round">ADR</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">
            <img :alt="match.map ? match.map : 'Map not found'"
                 :src="require('@/images/map_icons/map_icon_' + match.map + '.svg')"
                 :title="match.map"
                 class="map-icon">
          </td>
          <td class="td-rank text-center">
            <img
                :src="match.stats[0].extended?.rank?.new ? require('@/images/rank_icons/skillgroup' + match.stats[0].extended?.rank?.new + '.svg') : require('@/images/rank_icons/skillgroup0.svg')"
                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.enemy ? match.stats[0].extended.dmg.enemy : 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 :title="FormatFullDuration(match.duration)" class="td-duration text-center">
            {{ FormatDuration(match.duration) }}

          </td>
          <td :title="FormatFullDate(match.date)" class="td-date">
            <svg v-if="match.rounds === 16" class="bi bi-circle-half" fill="currentColor" height="16" viewBox="0 0 16 16" width="16"
                 xmlns="http://www.w3.org/2000/svg">
              <path d="M8 15A7 7 0 1 0 8 1v14zm0 1A8 8 0 1 1 8 0a8 8 0 0 1 0 16z"/>
            </svg>
            {{ FormatDate(match.date) }}
          </td>
        </tr>
        </tbody>
      </table>
      <h5 v-else>No matches on record</h5>
    </div>
  </div>
</template>

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

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

    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(`${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
            store.state.id64 = response.data.steamid64

            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) => {
            console.log(e);
          });
    }

    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,
      wl,
      props,
      GetUser,
      TrackMe,
      GetWinLoss,
      FormatDate,
      FormatFullDate,
      FormatDuration,
      FormatFullDuration,
      GoToMatch,
      GetHLTV_1
    }
  }
}
</script>

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

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

.win {
  background: linear-gradient(90deg, rgba(0, 255, 0, .2) 0%, rgba(0, 255, 0, .1) 5%, var(--bs-body-bg) 15%, var(--bs-body-bg) 100%);

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

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

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

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

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

table {
  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;
    }

    .td-map 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;
    }
  }
  .td-map 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, .adr, .duration, .hltv,
  .td-kills, .td-deaths, .td-assists, .td-plus, .td-adr, .td-duration, .td-hltv {
    display: none;
  }
}
</style>