export const SITE_URL = 'https://sba.manticorum.com'

export const CURRENT_SEASON = 8

export const MODERN_STAT_ERA_START = 8

export const GAMES_PER_SEASON = 72

// a type guard to tell typescript that undefined has been filtered and to only consider an array
// of the expected types (no undefineds) after filtering
export const isNotUndefined = <S>(value: S | undefined): value is S => value != undefined

export function avg(stat: { ab: number, hit: number }): number {
  if (stat.ab === 0) return 0

  return stat.hit / stat.ab
}

export function obp(stat: { pa: number, hit: number, bb: number, ibb: number, hbp: number }): number {
  if (stat.pa === 0) return 0

  return (stat.hit + stat.bb + stat.ibb + stat.hbp) / stat.pa
}

export function slg(stat: { ab: number, hit: number, double: number, triple: number, hr: number }): number {
  if (stat.ab === 0) return 0

  return (stat.hit + stat.double + (stat.triple * 2) + (stat.hr * 3)) / stat.ab
}

export function ops(stat: { pa: number, hit: number, bb: number, ibb: number, hbp: number, ab: number, double: number, triple: number, hr: number }): number {
  return obp(stat) + slg(stat)
}

export function woba(stat: { bb: number, hbp: number, hit: number, double: number, triple: number, hr: number, ab: number, ibb: number, sac: number }): number {
  const numerator = (.69 * stat.bb) + (.72 * stat.hbp) + (.89 * (stat.hit - stat.double - stat.triple - stat.hr)) + (1.27 * stat.double) + (1.62 * stat.triple) + (2.1 * stat.hr)
  const denominator = stat.ab + stat.bb - stat.ibb + stat.sac + stat.hbp

  if (denominator === 0) return 0

  return numerator / denominator
}

export function outsToInnings(stat: { outs: number }): string {
  return (stat.outs / 3).toFixed(1)
}

export function winPercentage(stat: { win: number, loss: number }): string {
  if (stat.win + stat.loss === 0) return '-'

  return (stat.win / (stat.win + stat.loss)).toFixed(3)
}

export function hitsPer9(stat: { outs: number, hits: number }): string {
  if (stat.outs === 0) return '-'

  return (stat.hits * 27 / stat.outs).toFixed(1)
}

export function hrsPer9(stat: { outs: number, hr: number }): string {
  if (stat.outs === 0) return '-'

  return (stat.hr * 27 / stat.outs).toFixed(1)
}
