<template>
  <div class="standings-table table-responsive-xl">
    <table class="table table-sm table-striped">
      <thead class="thead-dark">
        <tr>
          <th width="35%">Team</th>
          <th width="13%">Record</th>
          <th width="13%">Win %</th>
          <th width="13%">GB</th>
          <th width="13%">E#</th>
          <th width="13%">Run Diff</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(team, index) in sortedTeams" :key="index">
          <td>
            <RouterLink
              :to="{ name: 'team', params: { seasonNumber: seasonNumber(), teamAbbreviation: team.teamAbbreviation } }">
              {{ team.teamName }}
            </RouterLink>
          </td>
          <td>{{ record(team) }}</td>
          <td>{{ team.winPercentage }}</td>
          <td>{{ gamesBack(team) }}</td>
          <td>{{ eliminationNumber(team) }}</td>
          <td>{{ team.runDifferential }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script lang="ts">
import type { TeamStanding } from '@/services/standingsService'
import { CURRENT_SEASON } from '@/services/utilities'


export default {
  name: 'StandingsTable',
  props: {
    teams: {
      type: Array<TeamStanding>,
      required: true,
    },
    isDivisional: {
      type: Boolean,
      required: true
    }
  },
  computed: {
    sortedTeams(): TeamStanding[] {
      if (!this.teams) return []
      return this.teams.slice()
        .sort((t1, t2) =>
          (t2.wins - t2.losses) !== (t1.wins - t1.losses)
            ? (t2.wins - t2.losses) - (t1.wins - t1.losses)
            : (t2.wins + t2.losses) - (t1.wins + t1.losses))
    }
  },
  methods: {
    eliminationNumber(teamStanding: TeamStanding): string {
      return this.isDivisional ? teamStanding.divisionEliminationNumber : teamStanding.wildcardEliminationNumber
    },
    gamesBack(teamStanding: TeamStanding): string {
      return this.isDivisional ? teamStanding.divisionGamesBack : teamStanding.wildcardGamesBack
    },
    record(teamStanding: TeamStanding): string {
      return `${teamStanding.wins}-${teamStanding.losses}`
    },
    seasonNumber(): number {
      return CURRENT_SEASON
    }
  }
}
</script>
