<template>
  <div v-if="hasBattingStats" class="row" id="career-batting-row">
    <div class="col-sm-12">
      <h3>Batting Stats</h3>
      <div class="table-responsive-xl">
        <table class="table table-sm table-striped" id="career-batting">
          <thead class="thead-dark">
            <tr>
              <th @click="setKey('sortableSeason')" :class="getArrow('sortableSeason')">Season</th>
              <th @click="setKey('pa')" :class="getArrow('pa')">PA</th>
              <th @click="setKey('ab')" :class="getArrow('ab')">AB</th>
              <th @click="setKey('run')" :class="getArrow('run')">R</th>
              <th @click="setKey('hit')" :class="getArrow('hit')">H</th>
              <th @click="setKey('double')" :class="getArrow('double')">2B</th>
              <th @click="setKey('triple')" :class="getArrow('triple')">3B</th>
              <th @click="setKey('hr')" :class="getArrow('hr')">HR</th>
              <th @click="setKey('rbi')" :class="getArrow('rbi')">RBI</th>
              <th @click="setKey('sb')" :class="getArrow('sb')">SB</th>
              <th @click="setKey('cs')" :class="getArrow('cs')">CS</th>
              <th @click="setKey('bb')" :class="getArrow('bb')">BB</th>
              <th @click="setKey('so')" :class="getArrow('so')">SO</th>
              <th @click="setKey('avg')" :class="getArrow('avg')">BA</th>
              <th @click="setKey('obp')" :class="getArrow('obp')">OBP</th>
              <th @click="setKey('slg')" :class="getArrow('slg')">SLG</th>
              <th @click="setKey('ops')" :class="getArrow('ops')">OPS</th>
              <th @click="setKey('woba')" :class="getArrow('woba')">wOBA</th>
              <th @click="setKey('kPct')" :class="getArrow('kPct')">K%</th>
              <th @click="setKey('bphr')" :class="getArrow('bphr')">BPHR</th>
              <th @click="setKey('bpfo')" :class="getArrow('bpfo')">BPFO</th>
              <th @click="setKey('bp1b')" :class="getArrow('bp1b')">BP1B</th>
              <th @click="setKey('bplo')" :class="getArrow('bplo')">BPLO</th>
              <th @click="setKey('gidp')" :class="getArrow('gidp')">GIDP</th>
              <th @click="setKey('hbp')" :class="getArrow('hbp')">HBP</th>
              <th @click="setKey('sac')" :class="getArrow('sac')">SAC</th>
              <th @click="setKey('ibb')" :class="getArrow('ibb')">IBB</th>
            </tr>
          </thead>
          <tbody id="career-batting-table">
            <tr v-for="stat in sortedRegularAndPostSeasonBatting" :key="`${stat.seasonNumber}-${stat.isRegularSeason}`">
              <td>S{{ stat.seasonNumber }}{{ stat.isRegularSeason ? '' : ' / Playoffs' }}</td>
              <td>{{ stat.pa }}</td>
              <td>{{ stat.ab }}</td>
              <td>{{ stat.run }}</td>
              <td>{{ stat.hit }}</td>
              <td>{{ stat.double }}</td>
              <td>{{ stat.triple }}</td>
              <td>{{ stat.hr }}</td>
              <td>{{ stat.rbi }}</td>
              <td>{{ stat.sb }}</td>
              <td>{{ stat.cs }}</td>
              <td>{{ stat.bb }}</td>
              <td>{{ stat.so }}</td>
              <td>{{ stat.avg.toFixed(3) }}</td>
              <td>{{ stat.obp.toFixed(3) }}</td>
              <td>{{ stat.slg.toFixed(3) }}</td>
              <td>{{ stat.ops.toFixed(3) }}</td>
              <td>{{ stat.woba.toFixed(3) }}</td>
              <td>{{ calculateStrikeoutPercent(stat) }}</td>
              <td>{{ stat.bphr }}</td>
              <td>{{ stat.bpfo }}</td>
              <td>{{ stat.bp1b }}</td>
              <td>{{ stat.bplo }}</td>
              <td>{{ stat.gidp }}</td>
              <td>{{ stat.hbp }}</td>
              <td>{{ stat.sac }}</td>
              <td>{{ stat.ibb }}</td>
            </tr>
          </tbody>
          <tfoot>
            <tr v-for="(stat, idx) in careerBattingStats" :key="idx">
              <th>Career{{ idx > 0 ? ' / Playoffs' : '' }}</th>
              <th>{{ stat.pa }}</th>
              <th>{{ stat.ab }}</th>
              <th>{{ stat.run }}</th>
              <th>{{ stat.hit }}</th>
              <th>{{ stat.double }}</th>
              <th>{{ stat.triple }}</th>
              <th>{{ stat.hr }}</th>
              <th>{{ stat.rbi }}</th>
              <th>{{ stat.sb }}</th>
              <th>{{ stat.cs }}</th>
              <th>{{ stat.bb }}</th>
              <th>{{ stat.so }}</th>
              <th>{{ stat.avg.toFixed(3) }}</th>
              <th>{{ stat.obp.toFixed(3) }}</th>
              <th>{{ stat.slg.toFixed(3) }}</th>
              <th>{{ stat.ops.toFixed(3) }}</th>
              <th>{{ stat.woba.toFixed(3) }}</th>
              <th>{{ calculateStrikeoutPercent(stat) }}</th>
              <th>{{ stat.bphr }}</th>
              <th>{{ stat.bpfo }}</th>
              <th>{{ stat.bp1b }}</th>
              <th>{{ stat.bplo }}</th>
              <th>{{ stat.gidp }}</th>
              <th>{{ stat.hbp }}</th>
              <th>{{ stat.sac }}</th>
              <th>{{ stat.ibb }}</th>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { aggregateBattingStats, type BattingStat } from '@/services/battingStatsService'

interface BattingStatWithSeason extends BattingStat {
  seasonNumber: number
  isRegularSeason: boolean

  sortableSeason: string // constructed to sort S1 -> S1 Playoffs -> S2 -> etc

  kPct: string
}

export default {
  name: 'PlayerCareerBattingTable',
  props: {
    regularSeasonBattingStats: { type: Array<BattingStat>, required: true },
    postSeasonBattingStats: { type: Array<BattingStat>, required: true },
    showPostSeasonStats: { type: Boolean, required: true }
  },
  data() {
    return {
      sortKey: 'sortableSeason' as keyof BattingStatWithSeason,
      sortOrder: 1
    }
  },
  computed: {
    hasBattingStats(): boolean {
      return !!(this.regularSeasonBattingStats.length + this.postSeasonBattingStats.length)
    },
    careerBattingStats(): BattingStat[] {
      let careerStats = []

      if (this.regularSeasonBattingStats.length > 0) {
        careerStats.push(aggregateBattingStats(this.regularSeasonBattingStats))
      }

      if (this.showPostSeasonStats && this.postSeasonBattingStats.length > 0) {
        careerStats.push(aggregateBattingStats(this.postSeasonBattingStats))
      }

      return careerStats
    },
    sortedRegularAndPostSeasonBatting(): BattingStatWithSeason[] {
      let seasonStats: BattingStatWithSeason[] = []

      if (this.regularSeasonBattingStats?.length) {
        seasonStats = seasonStats.concat(this.regularSeasonBattingStats.map(stat => {
          return {
            ...stat,
            seasonNumber: stat.player.season,
            isRegularSeason: true,
            sortableSeason: `${`${stat.player.season}`.padStart(3, '0')}-A-Regular`,
            kPct: this.calculateStrikeoutPercent(stat)
          }
        }))
      }

      if (this.showPostSeasonStats && this.postSeasonBattingStats?.length) {
        seasonStats = seasonStats.concat(this.postSeasonBattingStats.map(stat => {
          return {
            ...stat,
            seasonNumber: stat.player.season,
            isRegularSeason: false,
            sortableSeason: `${`${stat.player.season}`.padStart(3, '0')}-B-Playoffs`,
            kPct: this.calculateStrikeoutPercent(stat)
          }
        }))
      }

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

      return this.sortOrder > 0 ? 'up' : 'down'
    },
    calculateStrikeoutPercent(stat: BattingStat): string {
      if (!stat.pa) return 'N/A'
      return (stat.so * 100 / stat.pa).toFixed(1)
    },
  }
}
</script>

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

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

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