#!/usr/local/bin/python
# -*- coding: UTF-8 -*-

import Cookie
import cgi
import cgitb; cgitb.enable()  # for troubleshooting
import Player
import os
import glob


thecookie = os.environ.get('HTTP_COOKIE')
C = Cookie.SimpleCookie()
C.load(thecookie)
me = C["username"].value
sc = C["score"].value

#To see if he is already battling
for i in glob.glob("*.txt"):
	if i.split(".")[0].startswith(me) or i.split(".")[0].endswith(me):
		print 'Location: http://students.washington.edu/zbadgerm/Math480/inbattle.cgi\n'


temp = []

flag = False
for i in open("lobby.txt", "r"):
	temp.append(i)
	if i.split(" ")[0].strip() == me.strip():
		flag = True

if flag == False:
	temp.append(me + " %s\n"%sc)

toWrite = open("lobby.txt", "w")

for i in temp:
	toWrite.write(i)
toWrite.close()


print "Content-type: text/html"
print
print """
<html>

<head><meta http-equiv="refresh" content="15"><link rel="stylesheet" type="text/css" href="battle.css" media="screen" />
<title>Sample CGI Script</title></head>

<body>
"""
print '<form method="post" action="fight.cgi">'
count = 0
toPrint = []
for i in open("lobby.txt", "r"):
	if me.strip() == i.split(" ")[0].strip():
		print '<p><b> You are %s. Your rating is %s</b></p>'%(i.split(" ")[0].strip(), sc)
		count = 1
	elif i != "\n":
		toPrint.append('<p>%s<input name = "enemy" type="submit" value = "%s"/></p>'%(i, i.split(" ")[0].strip()))

for i in toPrint:
	print i
print '</form>'

print """
</body>

</html>

""" 