<template>
  <div class="centerDiv">

    <!-- Teams and Score -->
    <div class="row">
      <div class="col-sm-3">
        <RouterLink v-if="adjacentGames?.team1prevGame" :to="{
          name: 'games', params: {
            seasonNumber: adjacentGames!.team1prevGame!.season,
            weekNumber: adjacentGames!.team1prevGame!.week,
            gameNumber: adjacentGames!.team1prevGame!.game_num,
            team1Abbreviation: adjacentGames!.team1prevGame!.away_team.abbrev,
            team2Abbreviation: adjacentGames!.team1prevGame!.home_team.abbrev
          }
        }" v-slot="{ href, navigate }">
          <button :href="href" @click="navigate" class="btn btn-sm btn-primary mx-1"
            :title="`Previous ${awayTeamAbbreviation} Game`">
            &lt;&lt;
          </button>
        </RouterLink>
        <RouterLink v-if="awayTeamAbbreviation && awayTeamThumbnail"
          :to="{ name: 'team', params: { seasonNumber: seasonNumber, teamAbbreviation: awayTeamAbbreviation } }">
          <img id="thumbnail" height="90" style="vertical-align:middle; max-height:100%;" :src="awayTeamThumbnail" />
        </RouterLink>
        <RouterLink v-if="adjacentGames?.team1nextGame" :to="{
          name: 'games', params: {
            seasonNumber: adjacentGames!.team1nextGame!.season,
            weekNumber: adjacentGames!.team1nextGame!.week,
            gameNumber: adjacentGames!.team1nextGame!.game_num,
            team1Abbreviation: adjacentGames!.team1nextGame!.away_team.abbrev,
            team2Abbreviation: adjacentGames!.team1nextGame!.home_team.abbrev
          }
        }" v-slot="{ href, navigate }">
          <button :href="href" @click="navigate" class="btn btn-sm btn-primary mx-1"
            :title="`Next ${awayTeamAbbreviation} Game`">
            &gt;&gt;
          </button>
        </RouterLink>
      </div>
      <div class="col-sm-6">
        <h1 class="text-center">{{ finalScore }}</h1>
        <h2 class="text-center">
          Season {{ seasonNumber }} - Week {{ weekNumber }} - Game {{ gameNumber }}
        </h2>
      </div>
      <div class="col-sm-3">
        <RouterLink v-if="adjacentGames?.team2prevGame" :to="{
          name: 'games', params: {
            seasonNumber: adjacentGames!.team2prevGame!.season,
            weekNumber: adjacentGames!.team2prevGame!.week,
            gameNumber: adjacentGames!.team2prevGame!.game_num,
            team1Abbreviation: adjacentGames!.team2prevGame!.away_team.abbrev,
            team2Abbreviation: adjacentGames!.team2prevGame!.home_team.abbrev
          }
        }" v-slot="{ href, navigate }">
          <button :href="href" @click="navigate" class="btn btn-sm btn-primary mx-1"
            :title="`Previous ${homeTeamAbbreviation} Game`">
            &lt;&lt;
          </button>
        </RouterLink>
        <RouterLink v-if="homeTeamAbbreviation && homeTeamThumbnail"
          :to="{ name: 'team', params: { seasonNumber: seasonNumber, teamAbbreviation: homeTeamAbbreviation } }">
          <img id="thumbnail" height="90" style="vertical-align:middle; max-height:100%;" :src="homeTeamThumbnail" />
        </RouterLink>
        <RouterLink v-if="adjacentGames?.team2nextGame" :to="{
          name: 'games', params: {
            seasonNumber: adjacentGames!.team2nextGame!.season,
            weekNumber: adjacentGames!.team2nextGame!.week,
            gameNumber: adjacentGames!.team2nextGame!.game_num,
            team1Abbreviation: adjacentGames!.team2nextGame!.away_team.abbrev,
            team2Abbreviation: adjacentGames!.team2nextGame!.home_team.abbrev
          }
        }" v-slot="{ href, navigate }">
          <button :href="href" @click="navigate" class="btn btn-sm btn-primary mx-1"
            :title="`Next ${homeTeamAbbreviation} Game`">
            &gt;&gt;
          </button>
        </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">

      <!-- Batting -->
      <div class="row">
        <!-- Away Batting -->
        <div class="col-xl-6">
          <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>
        </div>
        <!-- Home Batting -->
        <div class="col-xl-6">
          <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>
        </div>
      </div>
      <!-- Pitching -->
      <div class="row">
        <!-- Away Pitching -->
        <div class="col-xl-6">
          <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 Pitching -->
        <div class="col-xl-6">
          <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>

      <!-- Fielding -->
      <div class="row">
        <!-- Away Fielding -->
        <div class="col-xl-6">
          <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>
        </div>

        <!-- Home Team -->
        <div class="col-xl-6">
          <!-- 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>
        </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 { fetchGamesBySeasonAndTeamId, fetchSingleGame } from '@/services/gameService'
import { fetchPitchingStatsBySeries, type PitchingStat } from '@/services/pitchingStatsService'
import { fetchTeam } from '@/services/teamsService'
import { outsToInnings } from '@/services/utilities'

interface AdjacentGameHelper {
  team1prevGame: Game | undefined
  team1nextGame: Game | undefined
  team2prevGame: Game | undefined
  team2nextGame: Game | undefined
}

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[],
      adjacentGames: undefined as AdjacentGameHelper | undefined,
    }
  },
  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()
  },
  watch: {
    seasonNumber(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.clearData()
        this.fetchData()
      }
    },
    weekNumber(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.clearData()
        this.fetchData()
      }
    },
    gameNumber(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.clearData()
        this.fetchData()
      }
    },
    team1Abbreviation(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.clearData()
        this.fetchData()
      }
    },
    team2Abbreviation(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.clearData()
        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)

      await this.fetchAdjacentGames()
    },
    async fetchAdjacentGames(): Promise<void> {
      const team1Games = await fetchGamesBySeasonAndTeamId(this.seasonNumber, this.team1!.id)
      const team2Games = await fetchGamesBySeasonAndTeamId(this.seasonNumber, this.team2!.id)

      const prevGameNumber = this.gameNumber === 1 ? 4 : this.gameNumber - 1
      const nextGameNumber = this.gameNumber === 4 ? 1 : this.gameNumber + 1

      const prevWeekNumber = this.gameNumber === 1 ? this.weekNumber - 1 : this.weekNumber
      const nextWeekNumber = this.gameNumber === 4 ? this.weekNumber + 1 : this.weekNumber

      this.adjacentGames = {
        team1nextGame: team1Games.find(g => g.week === nextWeekNumber && g.game_num === nextGameNumber),
        team1prevGame: team1Games.find(g => g.week === prevWeekNumber && g.game_num === prevGameNumber),
        team2nextGame: team2Games.find(g => g.week === nextWeekNumber && g.game_num === nextGameNumber),
        team2prevGame: team2Games.find(g => g.week === prevWeekNumber && g.game_num === prevGameNumber)
      }
    },
    clearData(): void {
      this.team1 = undefined
      this.team2 = undefined
      this.game = undefined
      this.battingStats = []
      this.pitchingStats = []
      this.fieldingStats = []
      this.adjacentGames = undefined
    },
    outsToInnings(stat: PitchingStat): string {
      return outsToInnings(stat)
    },
  }
}
</script>
