import string;
import java.util.Date;
from java.text import SimpleDateFormat
import java.util.GregorianCalendar;

dateformat = SimpleDateFormat("MM/dd/yyyy");
shortformat = SimpleDateFormat("MM/dd");
dowformat = SimpleDateFormat("EEEEEEEEE");

class Team:
	def __init__(self,teamName,teamAbbrev,shirtColor):
		self.name = teamName;
		self.shirtColor = shirtColor;
		self.abbrevName = teamAbbrev;
	def __str__(self):
		return "Team: (%s) Shirt Color:(%s)" % (self.name,self.shirtColor);
		
	
class TeamFactory:
	def __init__ (self):
		self.teams = [];
	def createTeam(self,teamName,teamAbbrev,shirtColor):
		temp = Team(teamName,teamAbbrev,shirtColor);
		self.teams.append(temp);
		return temp;
	def getTeamsSortedByName(self):
		self.teams.sort(lambda x, y: cmp(string.lower(x.name), string.lower(y.name)));
		return self.teams;
		
		
class GameResult:
	pass;
	
class Score(GameResult):
	def __init__(self,scoreDictionary):
		self.scores = scoreDictionary;
		
class Forfeit(GameResult):	
	def __init__(self,forfeitList):
		self.forfeits;
		
class Postponed(GameResult):
	def __init__(self,reason = "Rained Out"):
		self.reason = reason;
	
class Day:
	def __init__(self,date,bringgear,takegear,description=None):
		self.games = [];
		self.date = date;
		self.bringgear = self.getNameGearTeam(bringgear);		
		self.takegear = self.getNameGearTeam(takegear);
		self.description = description;
		self.jdate = dateformat.parse(self.date);
		self.shortdate = shortformat.format(self.jdate)
		self.dow = dowformat.format(self.jdate)
		
	def addGame(self,game):
		self.games.append(game)
			
	def getNameGearTeam(self,team):
		if hasattr(team,'name'):
			return team.name;
		else:
			return team; #assuming its a string otherwise
			
		
class Week:
	def __init__(self,weeknum,description=""):
		self.days = None;
		self.description = description;
		self.weeknumber = weeknum;
	def addDay(self,day):
		if self.days == None:
			self.days = [day]
		else:
			self.days.append(day)
		


class Game:
	def __init__(self,time,field,team1,team2,refs):
		self.time = time;
		self.field = field;
		self.team1 = team1;
		self.team2 = team2;
		self.winner = 0;
		self.result = None;
		self.refs = refs;
		self.score = "";
	def addResult(self,result):
	
		self.result = result;
		if hasattr(result,"scores"):
			self.score = "%d - %d" % (result.scores[self.team1],result.scores[self.team2]);
			scoreDiff = result.scores[self.team1] - result.scores[self.team2]
			if (scoreDiff > 0):
				self.winner = 1;
			elif (scoreDiff < 0):
				self.winner = 2;
			else:
				self.winner = 0; #tie
		elif hasattr(result,"reason"):
			self.score = result.reason;
		
	def __str__(self):
		return "Game at %s on field %s refed by %s - %s vs %s" % (self.time,self.field,self.refs.name,self.team1.name,self.team2.name)
		
class Season:
	def __init__(self):	
		self.weeks = []
		self.teamfactory = TeamFactory();
		self.teams = self.teamfactory.teams;
	def addWeek(self,week):
		self.weeks.append(week)
	def standingSorter(self,s1,s2):
		if s1.W == s2.W:
			return s2.RD - s1.RD
		else: 
			return s2.W - s1.W
	
	def buildStandings(self):
		standings = {}
		for team in self.teams:
			standings[team] = StandingsLine(team)
		weekn = 0
		#print "season has %d weeks" % (len(season.weeks))
		for week in self.weeks:
			weekn+=1
		#	print weekn
			for day in week.days:
				for game in day.games:
				
					if hasattr(game.result,'scores'):
					
						t1stand = standings[game.team1]
						t2stand = standings[game.team2]
						t1stand.GP +=1
						t2stand.GP +=1
						t1score = game.result.scores[game.team1]
						t2score = game.result.scores[game.team2]
						
						if  t1score == t2score:
							t1stand.T += 1
							t2stand.T += 1
						else:
							t1stand.RD += t1score-t2score;
							t2stand.RD += t2score - t1score
							if 	t1score > t2score:
								t1stand.W += 1
								t2stand.L += 1
							else:
								t2stand.W +=1
								t1stand.L +=1
							
					elif hasattr(game.result,'forfeits'):
						t1stand = standings[game.team1]
						t2stand = standings[game.team2]
						t1stand.GP +=1
						t2stand.GP +=1
						print "TODO : keep track of forfeits";
						
		#NOW sort!
		s = standings.values();
		s.sort(self.standingSorter)
		#calcGB(s)
		return s;
		
	
			
		
		
class SeasonPrinter:
	def printSeason(self,season):
		weekNum = 0
		for week in season.weeks:
			weekNum = weekNum +1
			self.printWeek(week,weekNum)
	def printGame(self,game):
		winner1 = ""
		winner2 = ""
		if game.winner == 1:
			winner1 = " (Winner)"
		if game.winner == 2:
			winner2 = " (Winner)"
		
		p = "Time: %s Field %s %s%s vs. %s%s, %s" % (game.time,game.field,game.team1.name,winner1,game.team2.name,winner2,game.score)
		print p;
			
	def printWeek(self,week,weekNum):
		p = "Week %d" % weekNum
		if week.description != None:
			p = p + " - " + week.description
		print p
		for day in week.days:
			self.printDay(day)
	def printDay(self,day):
		if day.description != None:
			print "%s - %s "  % (self.formatDate(day.date),day.description)
		else:
			print "%s" % (self.formatDate(day.date))
		if len(day.games) > 0:
			print "Bringing gear: %s Taking gear: %s" % (day.bringgear,day.takegear)
			for game in day.games:
				self.printGame(game);
	
	def formatDate(self,date):
		return date
	def printStandings(self,standings):
		for standing in standings:
			print "%s %d-%d-%d-%d (%d) GB:(%f)" % (standing.teamName,standing.W,standing.L,standing.T,standing.F,standing.RD,standing.GB)


		
class StandingsLine:
	def __init__(self,team):
		self.team = team
		self.teamName = team.name
		self.W = self.L = self.T = self.F= self.GP = self.GB = self.RD = 0;




def calcGB(sortedStandings):
	bestW = sortedStandings[0].W
	bestL = sortedStandings[0].L
	for s in sortedStandings:
		s.GB = ((bestW - s.W) + (s.L - bestL))/2.0
	

 

