self = (if window? then window.PokeBattle.Tier ?= {} else this)

if !window?
  {Tiers} = require('./conditions')
  {_} = require('underscore')
  actualtiers = Tiers
else
  conditions = window.conditions ? {}
  actualtiers = Tiers
  _ = window._

self.Tiers =
 Unsorted:
   name      : "Unsorted"
   humanName : "Unsorted"
   tierRank  : -1
   playable  : false
 PA:
   name      : "PA"
   humanName : "Pathetic"
   tierRank  : 0
   playable  : false
 LC:
   name      : "LC"
   humanName : "Little Cup"
   tierRank  : 1
   playable  : false
 PU:
   name      : "PU"
   humanName : "Poorly Used"
   tierRank  : 2
   playable  : false
 NU:
   name      : "NU"
   humanName : "Never Used"
   tierRank  : 3
   playable  : false
 RU:
   name      : "RU"
   humanName : "Rarely Used"
   tierRank  : 4
   playable  : false
 UU:
   name      : "UU"
   humanName : "Under Used"
   tierRank  : 5
   playable  : true
   priority  : 1
 OU:
   name      : "OU"
   humanName : "Over Used"
   tierRank  : 6
   playable  : true
   priority  : 0
 Uber:
   name      : "Uber"
   humanName : "Ubers"
   tierRank  : 7
   playable  : true
   priority  : 2
 AG:
   name      : "AG"
   humanName : "Anything Goes"
   tierRank  : 8
   playable  : false

self.determineTier = (genData, pokemonArray) ->
  actualtiers = @Tiers
  if pokemonArray not instanceof Array then pokemonArray = [ pokemonArray ]
  tierrank = -1
  for pokemon in pokemonArray
    species = pokemon.species
    forme = pokemon.forme || "default"
    item = pokemon.item
    speciesData = genData?.FormeData[species]

    # Handle megas
    mega = genData?.ItemData[item]?.mega
    if mega
      [ megaSpecies, megaForme ] = mega
      if species == megaSpecies
        forme = megaForme

    # Get PBV of the Pokemon's forme
    tier = speciesData?[forme]?.tier[0] || 'Unsorted'
    tierdata = actualtiers[tier]

    tierdata = actualtiers['Unsorted'] if typeof tierdata == 'undefined'

    if tierdata.tierRank > tierrank
      tierrank = tierdata.tierRank

  actualtier = _.findWhere(actualtiers, {tierRank: tierrank});
  return actualtier