<template>
  <div v-if="fieldingStats.length" class="col-sm-6">
    <h3>Team Fielding {{ isRegularSeason ? '' : ' - Postseason' }}</h3>
    <div class="table-responsive-xl" style="max-width:40rem">
      <table class="table table-sm table-striped" id="table-fielding-stats">
        <thead class="thead-dark">
          <tr>
            <th @click="sortBy('playerName')" :class="getArrow('playerName')">Player</th>
            <th @click="sortBy('pos')" :class="getArrow('pos')">Pos</th>
            <th @click="sortBy('xCheckCount')" :class="getArrow('xCheckCount')">XCh</th>
            <th @click="sortBy('hit')" :class="getArrow('hit')">XH</th>
            <th @click="sortBy('error')" :class="getArrow('error')">E</th>
            <th @click="sortBy('passedBallCount')" :class="getArrow('passedBallCount')">PB</th>
            <th @click="sortBy('stolenBaseCheckCount')" :class="getArrow('stolenBaseCheckCount')">SBa</th>
            <th @click="sortBy('caughtStealingCount')" :class="getArrow('caughtStealingCount')">CSc</th>
            <th @click="sortBy('caughtStealingPercent')" :class="getArrow('caughtStealingPercent')">CS%</th>
            <th @click="sortBy('weightedFieldingPercent')" :class="getArrow('weightedFieldingPercent')">wF%</th>
          </tr>
        </thead>
        <tbody id="career-fielding-table">
          <tr v-for="stat in fieldingStats" :key="`${stat.player.name}-${stat.pos}`">
            <td>
              <RouterLink
                :to="{ name: 'player', params: { seasonNumber: seasonNumber, playerName: stat.player.name } }">
                {{ stat.player.name }}
              </RouterLink>
            </td>
            <td>{{ stat.pos }}</td>
            <td>{{ stat.xCheckCount }}</td>
            <td>{{ stat.hit }}</td>
            <td>{{ stat.error }}</td>
            <td>{{ stat.passedBallCount }}</td>
            <td>{{ stat.stolenBaseCheckCount }}</td>
            <td>{{ stat.caughtStealingCount }}</td>
            <td>{{ formatCaughtStealingPercent(stat) }}</td>
            <td>{{ formatWeightedFieldingPercent(stat) }}</td>
          </tr>
        </tbody>
        <tfoot>
          <tr v-for="stat in totalFieldingStat" id="career-fielding-footer" :key="stat.pos">
            <th>Total</th>
            <th>{{ stat.pos }}</th>
            <th>{{ stat.xCheckCount }}</th>
            <th>{{ stat.hit }}</th>
            <th>{{ stat.error }}</th>
            <th>{{ stat.passedBallCount }}</th>
            <th>{{ stat.stolenBaseCheckCount }}</th>
            <th>{{ stat.caughtStealingCount }}</th>
            <th>{{ formatCaughtStealingPercent(stat) }}</th>
            <th>{{ formatWeightedFieldingPercent(stat) }}</th>
          </tr>
        </tfoot>
      </table>
    </div>
  </div>
</template>
<script lang="ts">
import { aggregateFieldingStats, fetchFieldingStatsBySeasonAndTeamId, totaledFieldingStats, type FieldingStat } from '@/services/fieldingStatsService'
import { POS_MAP } from '@/services/utilities'

interface ExtendedFieldingStat extends FieldingStat {
  playerName: string
}

export default {
  name: 'TeamFieldingTable',
  props: {
    seasonNumber: { type: Number, required: true },
    teamId: { type: Number, required: true },
    isRegularSeason: { type: Boolean, required: true }
  },
  data() {
    return {
      fieldingStats: [] as ExtendedFieldingStat[],
      sortKey: 'xCheckCount' as keyof ExtendedFieldingStat,
      sortOrder: -1
    }
  },
  computed: {
    totalFieldingStat(): FieldingStat[] {
      if (this.fieldingStats.length > 0) {
        const totaledStats = aggregateFieldingStats(this.fieldingStats).sort((s1, s2) => POS_MAP[s1.pos] - POS_MAP[s2.pos])

        const allPositionsTotalStat = totaledFieldingStats(this.fieldingStats)
        if (allPositionsTotalStat !== undefined) {
          totaledStats.push(allPositionsTotalStat)
        }

        return totaledStats
      }

      return []
    }
  },
  created() {
    this.fetchData()
  },
  watch: {
    teamId(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.fieldingStats = []
        this.sortKey = 'xCheckCount'
        this.sortOrder = -1
        this.fetchData()
      }
    }
  },
  methods: {
    async fetchData(): Promise<void> {
      const unsortedFieldingStats: FieldingStat[] = await fetchFieldingStatsBySeasonAndTeamId(this.seasonNumber, this.teamId, this.isRegularSeason)
      this.fieldingStats = unsortedFieldingStats
        .map(s => ({ ...s, playerName: s.player.name }))
        .sort((s1, s2) => s2.xCheckCount - s1.xCheckCount)
    },
    formatCaughtStealingPercent(stat: FieldingStat): string {
      if (stat.stolenBaseCheckCount === 0 || Number.isNaN(stat.caughtStealingPercent)) {
        return '-'
      }

      return `${(stat.caughtStealingPercent * 100).toFixed(1)}%`
    },
    formatWeightedFieldingPercent(stat: FieldingStat): string {
      return stat.weightedFieldingPercent.toFixed(3)
    },
    sortBy(stat: keyof ExtendedFieldingStat): void {
      this.setKey(stat)

      if (stat === 'pos') {
        this.fieldingStats.sort((s1, s2) => this.sortOrder * (POS_MAP[s1.pos] - POS_MAP[s2.pos]))
        return
      }

      this.fieldingStats.sort((s1, s2) => s2[stat] < s1[stat] ? this.sortOrder : -1 * this.sortOrder)
    },
    setKey(stat: keyof ExtendedFieldingStat): void {
      if (this.sortKey === stat) {
        // if key currently selected, flip sort order
        this.sortOrder *= -1
      } else {
        this.sortKey = stat
        this.sortOrder = stat === 'playerName' ? 1 : -1
      }
    },
    getArrow(stat: keyof ExtendedFieldingStat): string {
      if (this.sortKey !== stat) return 'faux-arrow'

      return this.sortOrder > 0 ? 'up' : 'down'
    }
  }
}
</script>

<style>
.up::after {
  content: "▵"
}

.down::after {
  content: "▿"
}

.faux-arrow::after {
  opacity: 0;
  content: "▿"
}
</style>
