#!/usr/bin/python

def commify(n):
	s = str(n)
	i = 3
	while i < len(s):
		s = s[:-i] + ',' + s[-i:]
		i += 4
	return s

def ordinal(n):
	s = commify(n)
	if 10 <= n % 100 < 20:
		return s + 'th'
	else:
		return s + {1 : 'st', 2 : 'nd', 3 : 'rd'}.get(n % 10, "th")


import os
import sys
import cgi
import urllib
import re
import cgitb; cgitb.enable()
import menu

os.environ['PYTHON_EGG_CACHE'] = '/tmp'

import MySQLdb


try:
	db = MySQLdb.connect(host='lust',user='rftg',db='rftg')
except:
	print 'Content-type: text/html; charset=utf-8'
	print
	print '<html><body>The site is down for maintainence.</body></html>'
	sys.exit()


form = cgi.FieldStorage()

user = form.getvalue('user', '')

where = ''

if user:

	where = ' AND gid IN (SELECT gid FROM attendance JOIN users USING (uid) WHERE user="' + user + '")'

print 'Content-type: text/html; charset=utf-8'
print

cursor = db.cursor()

cursor.execute("""
	SELECT gid, description, COUNT(uid),
		GROUP_CONCAT(user ORDER BY uid SEPARATOR ', '),
                MAX(results.endvp)
	FROM games
	JOIN attendance USING (gid)
	JOIN users USING (uid)
	LEFT JOIN results USING (gid, uid)
	WHERE state='DONE'""" + where + """
	GROUP BY gid
	ORDER BY gid DESC
        LIMIT 1000""")

result = cursor.fetchall()

print '<html>'
print '<head>'
print '<title>Race for the Galaxy AI</title>'
print '<link rel="stylesheet" type="text/css" href="rftg.css" />'
print '<script type="text/javascript" src="sortable_new.js"></script>'
print '</head>'

print '<body>'

menu.printmenu()

print '<div align=center>'

print '<h1>COMPLETED GAMES</h1>'

print '<form action="games.cgi" method="get">'
print 'Filter by user: <input type="text" name="user" value="' + user + '">'
print '<input type="submit" value="Refresh">'
print '</form>'

print '<p>Click on the game ID to see more details.</p>'
print len(result), 'games displayed'

print '<table cellpadding=2 class="sortable" id="games">'

print '<thead>'
print '<tr>'
print '<th>Game ID</th>'
print '<th>Description</th>'
print '<th># Players</th>'
print '<th>Players</th>'
print '</tr>'
print '</thead>'
print '<tbody>'

alt = False

for r in result:

	if alt:
		print '<tr class="odd">'
	else:
		print '<tr class="even">'

	if r[4]:
		print '<td><a href="showgame.cgi?gid=' + str(r[0]) + '">'
		print r[0], '</td>'
	else:
		print '<td>', r[0], '</td>'
	print '<td>', r[1], '</td>'
	print '<td>', r[2], '</td>'
	print '<td>', r[3], '</td>'

	print '</tr>'

	alt = not alt

print '</tbody></table>'

print '</div>'

print '<hr>'

print '<p class="footer">'
print 'Send questions, suggestions or comments to '
print '<a href="mailto:keldon@keldon.net">keldon@keldon.net</a>'
print '</p>'

print '</body></html>'
