<template>
  <div class="centerDiv">

    <!-- Teams and Score -->
    <div class="row">
      <div class="col-sm-2">
        <RouterLink v-if="awayTeamAbbreviation && awayTeamThumbnail"
          :to="{ name: 'team', params: { seasonNumber: seasonNumber, teamAbbreviation: awayTeamAbbreviation } }">
          <img id="thumbnail" height="90" style="float:right; vertical-align:middle; max-height:100%;"
            :src="awayTeamThumbnail" />
        </RouterLink>
      </div>
      <div class="col-sm">
        <h1 class="text-center">{{ finalScore }}</h1>
        <h2 class="text-center">
          Season {{ seasonNumber }} - Week {{ weekNumber }} - Game {{ gameNumber }}
        </h2>
      </div>
      <div class="col-sm-2">
        <RouterLink v-if="homeTeamAbbreviation && homeTeamThumbnail"
          :to="{ name: 'team', params: { seasonNumber: seasonNumber, teamAbbreviation: homeTeamAbbreviation } }">
          <img id="thumbnail" height="90" style="float:right; vertical-align:middle; max-height:100%;"
            :src="homeTeamThumbnail" />
        </RouterLink>
      </div>
    </div>

    <!-- Pitcher Decisions and Sheet Link -->
    <div class="row">
      <h6 style="text-align: center;">
        {{ pitcherDecisions }}
        <a v-if="isAuthenticated && sheetsUrl" target="_blank" :href="sheetsUrl" title="Link to scorecard">
          🡵
        </a>
      </h6>
    </div>

    <!-- Full Scorecard -->
    <div class="row" id="scorecard">

      <!-- Away Team -->
      <div class="col-xl-6">

        <!-- Away Batting -->
        <h3 id="awayteam-batting-header">{{ awayTeamName }} Batting</h3>
        <div class="table-responsive-xl">
          <table class="table table-sm table-striped" id="away-batting">
            <thead class="thead-dark">
              <tr>
                <th>Player</th>
                <th>PA</th>
                <th>AB</th>
                <th>R</th>
                <th>H</th>
                <th>2B</th>
                <th>3B</th>
                <th>HR</th>
                <th>RBI</th>
                <th>SB</th>
                <th>CS</th>
                <th>BB</th>
                <th>SO</th>
                <th>GIDP</th>
                <th>HBP</th>
                <th>SAC</th>
                <th>IBB</th>
              </tr>
            </thead>
            <tbody id="awayteam-batting-table">
              <tr v-for="stat in awayTeamBattingStats" :key="stat.player.name">
                <td>
                  <RouterLink
                    :to="{ name: 'player', params: { seasonNumber: seasonNumber, playerName: stat.player.name } }">
                    {{ stat.player.name }}
                  </RouterLink>
                </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.gidp }}</td>
                <td>{{ stat.hbp }}</td>
                <td>{{ stat.sac }}</td>
                <td>{{ stat.ibb }}</td>
              </tr>
            </tbody>
            <tfoot></tfoot>
          </table>
        </div>

        <!-- Away Fielding -->
        <h3 id="awayteam-fielding-header">{{ awayTeamName }} Fielding</h3>
        <div class="table-responsive-xl">
          <table class="table table-sm table-striped" style="max-width: 25rem" id="away-fielding">
            <thead class="thead-dark">
              <tr>
                <th>Player</th>
                <th>X-Ch</th>
                <th>X-Hit</th>
                <th>Error</th>
                <th>PB</th>
                <th>SBa</th>
                <th>CSc</th>
              </tr>
            </thead>
            <tbody id="awayteam-fielding-table">
              <tr v-for="stat in awayTeamFieldingStats" :key="stat.player.name">
                <td>
                  <RouterLink
                    :to="{ name: 'player', params: { seasonNumber: seasonNumber, playerName: stat.player.name } }">
                    {{ stat.player.name }}
                  </RouterLink>
                </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>
              </tr>
            </tbody>
            <tfoot></tfoot>
          </table>
        </div>

        <!-- Away Pitching -->
        <h3 id="awayteam-pitching-header">{{ awayTeamName }} Pitching</h3>
        <div class="table-responsive-xl">
          <table class="table table-sm table-striped" style="max-width: 50rem" id="away-pitching">
            <thead class="thead-dark">
              <tr>
                <th>Player</th>
                <th>W</th>
                <th>L</th>
                <th>SV</th>
                <th>HD</th>
                <th>BSV</th>
                <th>IP</th>
                <th>H</th>
                <th>R</th>
                <th>ER</th>
                <th>HR</th>
                <th>BB</th>
                <th>SO</th>
                <th>HBP</th>
                <th>BK</th>
                <th>WP</th>
              </tr>
            </thead>
            <tbody id="awayteam-pitching-table">
              <tr v-for="stat in awayTeamPitchingStats" :key="stat.player.name">
                <td>
                  <RouterLink
                    :to="{ name: 'player', params: { seasonNumber: seasonNumber, playerName: stat.player.name } }">
                    {{ stat.player.name }}
                  </RouterLink>
                </td>
                <td>{{ stat.win }}</td>
                <td>{{ stat.loss }}</td>
                <td>{{ stat.save }}</td>
                <td>{{ stat.hold }}</td>
                <td>{{ stat.bsave }}</td>
                <td>{{ outsToInnings(stat) }}</td>
                <td>{{ stat.hits }}</td>
                <td>{{ stat.run }}</td>
                <td>{{ stat.e_run }}</td>
                <td>{{ stat.hr }}</td>
                <td>{{ stat.bb }}</td>
                <td>{{ stat.so }}</td>
                <td>{{ stat.hbp }}</td>
                <td>{{ stat.balk }}</td>
                <td>{{ stat.wp }}</td>
              </tr>
            </tbody>
            <tfoot></tfoot>
          </table>
        </div>
      </div>

      <!-- Home Team -->
      <div class="col-xl-6">

        <!-- Home Batting -->
        <h3 id="hometeam-batting-header">{{ homeTeamName }} Batting</h3>
        <div class="table-responsive-xl">
          <table class="table table-sm table-striped" id="home-batting">
            <thead class="thead-dark">
              <tr>
                <th>Player</th>
                <th>PA</th>
                <th>AB</th>
                <th>R</th>
                <th>H</th>
                <th>2B</th>
                <th>3B</th>
                <th>HR</th>
                <th>RBI</th>
                <th>SB</th>
                <th>CS</th>
                <th>BB</th>
                <th>SO</th>
                <th>GIDP</th>
                <th>HBP</th>
                <th>SAC</th>
                <th>IBB</th>
              </tr>
            </thead>
            <tbody id="hometeam-batting-table">
              <tr v-for="stat in homeTeamBattingStats" :key="stat.player.name">
                <td>
                  <RouterLink
                    :to="{ name: 'player', params: { seasonNumber: seasonNumber, playerName: stat.player.name } }">
                    {{ stat.player.name }}
                  </RouterLink>
                </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.gidp }}</td>
                <td>{{ stat.hbp }}</td>
                <td>{{ stat.sac }}</td>
                <td>{{ stat.ibb }}</td>
              </tr>
            </tbody>
            <tfoot></tfoot>
          </table>
        </div>

        <!-- Home Fielding -->
        <h3 id="hometeam-fielding-header">{{ homeTeamName }} Fielding</h3>
        <div class="table-responsive-xl">
          <table class="table table-sm table-striped" style="max-width: 25rem" id="home-fielding">
            <thead class="thead-dark">
              <tr>
                <th>Player</th>
                <th>X-Ch</th>
                <th>X-Hit</th>
                <th>Error</th>
                <th>PB</th>
                <th>SBa</th>
                <th>CSc</th>
              </tr>
            </thead>
            <tbody id="hometeam-fielding-table">
              <tr v-for="stat in homeTeamFieldingStats" :key="stat.player.name">
                <td>
                  <RouterLink
                    :to="{ name: 'player', params: { seasonNumber: seasonNumber, playerName: stat.player.name } }">
                    {{ stat.player.name }}
                  </RouterLink>
                </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>
              </tr>
            </tbody>
            <tfoot></tfoot>
          </table>
        </div>

        <!-- Home Pitching -->
        <h3 id="hometeam-pitching-header">{{ homeTeamName }} Pitching</h3>
        <div class="table-responsive-xl">
          <table class="table table-sm table-striped" style="max-width: 50rem" id="home-pitching">
            <thead class="thead-dark">
              <tr>
                <th>Player</th>
                <th>W</th>
                <th>L</th>
                <th>SV</th>
                <th>HD</th>
                <th>BSV</th>
                <th>IP</th>
                <th>H</th>
                <th>R</th>
                <th>ER</th>
                <th>HR</th>
                <th>BB</th>
                <th>SO</th>
                <th>HBP</th>
                <th>BK</th>
                <th>WP</th>
              </tr>
            </thead>
            <tbody id="hometeam-pitching-table">
              <tr v-for="stat in homeTeamPitchingStats" :key="stat.player.name">
                <td>
                  <RouterLink
                    :to="{ name: 'player', params: { seasonNumber: seasonNumber, playerName: stat.player.name } }">
                    {{ stat.player.name }}
                  </RouterLink>
                </td>
                <td>{{ stat.win }}</td>
                <td>{{ stat.loss }}</td>
                <td>{{ stat.save }}</td>
                <td>{{ stat.hold }}</td>
                <td>{{ stat.bsave }}</td>
                <td>{{ outsToInnings(stat) }}</td>
                <td>{{ stat.hits }}</td>
                <td>{{ stat.run }}</td>
                <td>{{ stat.e_run }}</td>
                <td>{{ stat.hr }}</td>
                <td>{{ stat.bb }}</td>
                <td>{{ stat.so }}</td>
                <td>{{ stat.hbp }}</td>
                <td>{{ stat.balk }}</td>
                <td>{{ stat.wp }}</td>
              </tr>
            </tbody>
            <tfoot></tfoot>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import type { Game, Team } from '@/services/apiResponseTypes'
import { isDiscordAuthenticated } from '@/services/authenticationService'
import { fetchBattingStatsBySeries, type BattingStat } from '@/services/battingStatsService'
import { fetchFieldingStatsBySeries, type FieldingStat } from '@/services/fieldingStatsService'
import { fetchSingleGame } from '@/services/gameService'
import { fetchPitchingStatsBySeries, type PitchingStat } from '@/services/pitchingStatsService'
import { fetchTeam } from '@/services/teamsService'
import { outsToInnings } from '@/services/utilities'

export default {
  name: 'GameView',
  data() {
    return {
      isAuthenticated: false as boolean,
      team1: undefined as Team | undefined,
      team2: undefined as Team | undefined,
      game: undefined as Game | undefined,
      battingStats: [] as BattingStat[],
      pitchingStats: [] as PitchingStat[],
      fieldingStats: [] as FieldingStat[],
    }
  },
  props: {
    seasonNumber: { type: Number, required: true },
    weekNumber: { type: Number, required: true },
    gameNumber: { type: Number, required: true },
    team1Abbreviation: { type: String, required: true },
    team2Abbreviation: { type: String, required: true }
  },
  computed: {
    awayTeamThumbnail(): string {
      if (!this.game) return ''
      return this.game.away_team.thumbnail
    },
    homeTeamThumbnail(): string {
      if (!this.game) return ''
      return this.game.home_team.thumbnail
    },
    awayTeamAbbreviation(): string {
      if (!this.game) return ''
      return this.game.away_team.abbrev
    },
    homeTeamAbbreviation(): string {
      if (!this.game) return ''
      return this.game.home_team.abbrev
    },
    awayTeamName(): string {
      if (!this.game) return ''
      return this.game.away_team.sname
    },
    homeTeamName(): string {
      if (!this.game) return ''
      return this.game.home_team.sname
    },
    finalScore(): string {
      if (!this.game) return ''
      return `${this.awayTeamAbbreviation} ${this.game?.away_score} @ ${this.game?.home_score} ${this.homeTeamAbbreviation}`
    },
    homeTeamBattingStats(): BattingStat[] {
      return this.battingStats.filter(bs => bs.game !== 'TOT'
        && bs.game.game_num === this.gameNumber
        && bs.team.abbrev === this.homeTeamAbbreviation)
    },
    homeTeamPitchingStats(): PitchingStat[] {
      return this.pitchingStats.filter(ps => ps.game !== 'TOT'
        && ps.game.game_num === this.gameNumber
        && ps.team.abbrev === this.homeTeamAbbreviation)
    },
    homeTeamFieldingStats(): FieldingStat[] {
      return this.fieldingStats.filter(fs => fs.game !== 'TOT'
        && fs.game.game_num === this.gameNumber
        && fs.team.abbrev === this.homeTeamAbbreviation)
    },
    awayTeamBattingStats(): BattingStat[] {
      return this.battingStats.filter(bs => bs.game !== 'TOT'
        && bs.game.game_num === this.gameNumber
        && bs.team.abbrev === this.awayTeamAbbreviation)
    },
    awayTeamPitchingStats(): PitchingStat[] {
      return this.pitchingStats.filter(ps => ps.game !== 'TOT'
        && ps.game.game_num === this.gameNumber
        && ps.team.abbrev === this.awayTeamAbbreviation)
    },
    awayTeamFieldingStats(): FieldingStat[] {
      return this.fieldingStats.filter(fs => fs.game !== 'TOT'
        && fs.game.game_num === this.gameNumber
        && fs.team.abbrev === this.awayTeamAbbreviation)
    },
    sheetsUrl(): string | undefined {
      return this.game?.scorecard_url
    },
    pitcherDecisions(): string {
      const decisions = this.homeTeamPitchingStats.concat(this.awayTeamPitchingStats).filter(ps => ps.win || ps.loss || ps.hold || ps.save || ps.bsave)
      const win = decisions.find(d => d.win)
      const loss = decisions.find(d => d.loss)
      const holds = decisions.filter(d => d.hold)
      const save = decisions.find(d => d.save)
      const blownSaves = decisions.filter(d => d.bsave)

      const decisionStrings = []
      if (win) decisionStrings.push(`Win: ${win.player.name}`)
      if (loss) decisionStrings.push(`Loss: ${loss.player.name}`)
      if (holds.length) {
        decisionStrings.push(`Hold${holds.length > 1 ? 's' : ''}: ${holds.map(h => h.player.name).join(', ')}`)
      }
      if (save) decisionStrings.push(`Save: ${save.player.name}`)
      if (blownSaves.length) {
        decisionStrings.push(`Blown Save${blownSaves.length > 1 ? 's' : ''}: ${blownSaves.map(h => h.player.name).join(', ')}`)
      }


      return decisionStrings.join(' | ')
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData(): Promise<void> {
      this.isAuthenticated = await isDiscordAuthenticated()

      this.team1 = await fetchTeam(this.seasonNumber, this.team1Abbreviation)
      this.team2 = await fetchTeam(this.seasonNumber, this.team2Abbreviation)

      if (!this.team1 || !this.team2) return

      this.game = await fetchSingleGame(this.seasonNumber, this.weekNumber, this.gameNumber, this.team1.id, this.team2.id)
      this.battingStats = await fetchBattingStatsBySeries(this.seasonNumber, this.weekNumber, this.team1.id, this.team2.id)
      this.pitchingStats = await fetchPitchingStatsBySeries(this.seasonNumber, this.weekNumber, this.team1.id, this.team2.id)
      this.fieldingStats = await fetchFieldingStatsBySeries(this.seasonNumber, this.weekNumber, this.team1.id, this.team2.id)
    },
    outsToInnings(stat: PitchingStat): string {
      return outsToInnings(stat)
    },
  }
}
</script>