<template>
  <div>
    <div class="md-layout md-alignment-top-center md-scrollbar" style="height: 400px; overflow-y: auto;" v-if="player !== null">
      <div :class="`md-layout-item md-size-${f_size} md-small-size-100`">
        <h4 style="margin: 10% 0%" v-on:click="copyS64()" class="clickable">{{player !== null && player['steam_data'] !== null?player['steam_data']['nickname']:'игрок'}}
          <md-tooltip class="tooltip" md-direction="bottom">Скопировать Steam64 в буфер обмена</md-tooltip>
        </h4>
        <hr>
        <div v-if="player['ban'] !== null">
          <p class="profile-text" style="display: inline">Статус Бана: </p>
          <p class="profile-text" style="color: brown; display: inline">Забанен</p>
          <p class="profile-text clickable" v-on:click="$refs.bvd_pc.showMe(true, player['ban'])">О бане...</p>
        </div>
        <div v-if="player['permition'] === null">
          <p class="profile-text" style="display: inline">Статус VIP : </p>
          <p class="profile-text" style="color: crimson;display: inline"> слыш купи</p>
        </div>
        <div v-else>
          <p class="profile-text" style="display: inline">Статус {{player['permition']['status']}} : </p>
          <p class="profile-text" style="color: green;display: inline" v-if="player['permition']['status'] === 'VIP'"> Куплен</p>
          <p class="profile-text" v-else style="color: #fd8846;display: inline">Имеется</p>
          <br>
          <p class="profile-text" style="display: inline">Дата окончания : </p>
          <p class="profile-text" v-if="player['permition']['amount'] === 0" style="display: inline">Навсегда</p>
          <p class="profile-text" v-else style="display: inline">{{new Date((player['permition']['u_timestamp'] + player['permition']['amount']) * 1000).toLocaleDateString()}}</p>
        </div>
        <hr>
        <!--GAMETIME-->
        <md-button v-on:click="loadingUserTime()" v-if="usertime.loaded === false" class="md-raised btn-strange" style="margin: 0% 0%" md-menu-trigger>{{usertime.loading?'Загрузка':'Статистика по картам'}}
          <md-tooltip class="tooltip" md-direction="right">Нажми на сервер чтоб узнать ранг и когда играл</md-tooltip>
        </md-button>
        <md-menu v-else md-direction="bottom-start" md-size="auto">
          <md-button class="md-raised btn-strange" md-menu-trigger>Статистика по картам</md-button>
          <md-menu-content>
            <md-menu-item v-for="g in usertime.store" :key="g[0]+'g'" v-on:click="$refs.pc_gd.showMe(true, player['steamids']['steam64'], g[2], g[1])">{{g[0]}} - {{timeFormat(g[1])}}</md-menu-item>
          </md-menu-content>
        </md-menu>
        <div style="padding: 1% 0%"/>
        <md-menu md-direction="bottom-start" md-size="auto">
          <md-button class="md-raised btn-strange" md-menu-trigger>Последние игры
            <md-tooltip class="tooltip" md-direction="right">Дата последний игры на одном из серверов</md-tooltip>
          </md-button>
          <md-menu-content>
            <md-menu-item v-for="l in getLastPlay()" :key="l[0]+'l'" v-on:click="$refs.pc_gd.showMe(true, player['steamids']['steam64'], l[2])">{{l[0]}} - {{l[1]}}</md-menu-item>
          </md-menu-content>
        </md-menu>
        <GametimeDialog ref="pc_gd"/>
        <div style="padding: 1% 0%"/>
        <!--DONATES-->
        <md-button v-on:click="loadingDonates()" v-if="donates.loaded === false" class="md-raised btn-strange" style="margin: 0% 0%" md-menu-trigger>{{donates.loading?'Загрузка':'Покупки VIP'}}
          <md-tooltip class="tooltip" md-direction="right">Список покупок привелегий</md-tooltip>
        </md-button>
        <md-menu v-else md-direction="bottom-start" md-size="auto">
          <md-button class="md-raised btn-strange" md-menu-trigger>Покупки VIP</md-button>
          <md-menu-content>
            <md-menu-item v-for="d in donates.store" :key="d['utime']+'d'">{{new Date(d['utime'] * 1000).toLocaleDateString()}} | {{d['status']}}</md-menu-item>
          </md-menu-content>
        </md-menu>
        <div style="padding: 1% 0%"/>
        <!--BAN LIST-->
        <md-button v-on:click="loadingBanList()" v-if="ban_list.loaded === false" class="md-raised btn-strange" style="margin: 0% 0%" md-menu-trigger>{{ban_list.loading?'Загрузка':'История банов'}}
          <md-tooltip class="tooltip" md-direction="right">Нажми на бан чтоб узнать подробности</md-tooltip>
        </md-button>
        <md-menu v-else md-direction="bottom-start" md-size="auto">
          <md-button class="md-raised btn-strange" md-menu-trigger>История Банов</md-button>
          <md-menu-content>
            <md-menu-item v-on:click="$refs.bvd_pc.showMe(true, b)" v-for="b in ban_list.store" :key="b['id']+'b'">#{{b['id']}} | {{new Date(b['ban_utime'] * 1000).toLocaleDateString()}} | {{b['ban_length']===0?'Навсегда':`${b['ban_length']} минут`}}</md-menu-item>
          </md-menu-content>
        </md-menu>
        <BanViewDialog ref="bvd_pc"/>
        <div style="padding: 1% 0%"/>
        <!--ALT ACCOUNTS-->
        <md-button v-on:click="loadingAltList()" v-if="this.$API.admin.permition.alt === true && altaccount.loaded === false" class="md-raised btn-strange" style="margin: 0% 0%" md-menu-trigger>{{altaccount.loading?'Загрузка':'Альт.аккаунты'}}
          <md-tooltip class="tooltip" md-direction="right">Пельмень путис</md-tooltip>
        </md-button>
        <md-menu v-if="this.$API.admin.permition.alt === true && altaccount.loaded === true" md-direction="bottom-start" md-size="auto">
          <md-button class="md-raised btn-strange" md-menu-trigger>Альт.аккаунты</md-button>
          <md-menu-content>
            <md-menu-item v-for="b in altaccount.store" :key="b" v-on:click="$refs.alt_ipv.getPlayerWithSteam(b)">{{b}}</md-menu-item>
          </md-menu-content>
        </md-menu>
        <ProfileViewer_Internal :steam64="player['steamids']['steam64']" ref="alt_ipv" id="alt_ipv"/>
      </div>
      <div :class="`md-layout-item md-size-${f_size} md-small-size-100`">
        <div style="justify-content: right; display: flex; padding: 10% 0%">
          <img :src="getAvatar()" style="border-radius: 15px;">
        </div>
        <p class="profile-text" style="text-align: right; cursor: pointer;" v-if="this.player['play_on'] !== null && 'ip' in this.player['play_on']" v-on:click="showIP()">IP : {{player_ip}}</p>
        <p class="profile-text" style="text-align: right; cursor: pointer;" v-if="this.player['play_on'] !== null && 'country' in this.player['play_on']">Страна : {{this.player['play_on']['country']}}</p>
        <p class="profile-text" style="text-align: right" v-if="this.player['play_on'] !== null && 'kills' in this.player['play_on']">Убийств : {{this.player['play_on']['kills']}}</p>
        <p class="profile-text" style="text-align: right" v-if="this.player['play_on'] !== null && 'deads' in this.player['play_on']">Смертей : {{this.player['play_on']['deads']}}</p>
        <p class="profile-text" style="text-align: right; cursor: pointer" v-on:click="loadingUserTime()">Наиграно : {{usertime.total}}</p>
        <div style="justify-content: right; display: flex">
          <DiscordSvg :h="'10%'" :w="'40'" style="margin-left: 5%" v-if="this.player['attached_discords'].filter(v => v['active'] === 1).length>0" :url="`https://discord.com/channels/@me/${this.player['attached_discords'].filter(v => v['active'] === 1)[0]['discord_id']}`"/>
          <SteamSvg :h="'10%'" :w="'40'" style="margin-left: 5%;" :url="this.player['steamids']['community_url']"/>
        </div>
      </div>
      <br>
    </div>
    <SnackLoader ref="profile_snack" s_text="Steam64 скопирован в буфер обмена" :dura="2000"/>
  </div>
</template>

<script>
import DiscordSvg from "@/components/Others/CustomSvg/DiscordSvg.vue";
import SteamSvg from "@/components/Others/CustomSvg/SteamSvg.vue";
import axios from "axios";
import SnackLoader from "@/components/Others/Loader/SnackLoader.vue";
import Random from "@/api/Random";
import BanViewDialog from "@/components/ActionDialogs/BanViewDialog.vue";
import GametimeDialog from "@/components/ActionDialogs/GametimeDialog.vue";

export default {
  name: "ProfileContainer",
  components: {
    GametimeDialog,
    BanViewDialog,
    SnackLoader, ProfileViewer_Internal: () => import("@/components/Others/Loader/ProfileViewer.vue"), SteamSvg, DiscordSvg},
  props: {
    player: Object,
    f_size: {
      type: Number,
      default: 45
    },
  },
  data: () => ({
    player_ip: "Показать",
    donates: {
      loading: false,
      loaded: false,
      store: []
    },
    ban_list: {
      loading: false,
      loaded: false,
      store: []
    },
    usertime: {
      loading: false,
      loaded: false,
      store: [],
      total: "Показать"
    },
    altaccount: {
      loading: false,
      loaded: false,
      store:[]
    }
  }),
  methods: {
    getAvatar() {
      try {
        return this.player.steam_data['avatar'];
      } catch (err) {
        return require('@/assets/profile-user.svg');
      }
    },
    timeFormat(seconds) {
      return this.$API.UNIX2FACTI_TIME(seconds);
    },
    getLastPlay() {
      return this.$API.player.getLastplayList(this.player);
    },
    copyS64() {
      navigator.clipboard.writeText(this.player['steamids']['steam64']);
      this.$refs.profile_snack.setLoading(true);
    },
    showIP() {
      if (this.player_ip.indexOf(":") !== -1) {
        this.player_ip = "Показать";
        return;
      }
      axios.options("api/crypto" + Random.getRndWebNew()).then((response) => {
        this.player_ip = "ждем...";
        if (response.status === 200) {
          axios.post("api/crypto/decrypt" + Random.getRndWebNew(), {"ip":this.player['play_on']['ip']}).then(response => {
            this.player_ip = response.data['ip'];
          })
        }
      }).catch(() => {
        this.player_ip = "хаха нет";
      })
    },
    loadingDonates(){
      if (this.donates.loading) return;
      this.donates.loading = true;
      axios.get(`api/profile/web?steam64=${this.player['steamids']['steam64']}&requests=donates` + Random.getRndWebAppend())
          .then(response => {
            this.donates.store = response.data['donates'];
            this.donates.loaded = true;
          })
          .catch(() => this.donates.loaded = false)
          .finally(() => this.donates.loading = false)

    },
    loadingBanList(){
      if (this.ban_list.loading || this.ban_list.loaded) return;
      this.ban_list.loading = true;
      axios.get(`api/profile/web?steam64=${this.player['steamids']['steam64']}&requests=ban_list` + Random.getRndWebAppend())
          .then(response => {
            this.ban_list.store = response.data['ban_list'];
            this.ban_list.loaded = true;
          })
          .catch(() => this.ban_list.loaded = false)
          .finally(() => this.ban_list.loading = false)
    },
    loadingUserTime(){
      if (this.usertime.loading || this.usertime.loaded) return;
      this.usertime.loading = true;
      this.usertime.total = "считаем сколько";
      axios.get(`api/profile/web?steam64=${this.player['steamids']['steam64']}&requests=usertime` + Random.getRndWebAppend())
          .then(response => {
            this.usertime.store = this.$API.player.getGametime(this.$API, response.data['gametime']);
            this.usertime.total = this.timeFormat(this.$API.player.getGametimeTotal(response.data['gametime']));
            this.usertime.loaded = true;
          })
          .catch(() => this.usertime.loaded = false)
          .finally(() => this.usertime.loading = false)
    },
    loadingAltList(){
      if (this.altaccount.loading || this.altaccount.loaded) return;
      this.altaccount.loading = true;
      axios.get(`api/admin/db/alt?steam64=${this.player['steamids']['steam64']}` + Random.getRndWebAppend())
          .then(response => {
            if (response.status === 200) {
              this.altaccount.store = response.data.map(url => url.split('/').pop()).filter(s64 => s64 !== this.player['steamids']['steam64']);
              this.altaccount.loaded = true;
            }
          })
          .catch(() => this.altaccount.loaded = false)
          .finally(() => this.altaccount.loading = false)
    }
  }
}
</script>

<style>
.profile-text {
  text-align: left;
  font-size: 1.5em;
}

.md-menu-content {
  z-index: 111;
  max-width: unset;
}

.tooltip {
  background: rgba(0, 0, 0, 0.7);
  font-family: tf2secondary;
  color: #fd8846;
}
</style>