#!/usr/local/bin/python
# -*- coding: UTF-8 -*-

import Cookie
import cgi
import cgitb; cgitb.enable()  # for troubleshooting
import Player
import os

thecookie = os.environ.get('HTTP_COOKIE')
C = Cookie.SimpleCookie()
C.load(thecookie)

enemy = C["enemy"].value
me = C["username"].value
bf = C["field"].value

temp = []
j = 0
for i in open("%s.txt"%(bf), "r"):
	temp.append(i)
	
if temp[1].split("|")[0].startswith(me):
	p1 = Player.Player(temp[1].split("|")[1],temp[1].split("|")[2])
	p2 = Player.Player(temp[2].split("|")[1],temp[2].split("|")[2])
else:
	p1 = Player.Player(temp[2].split("|")[1],temp[2].split("|")[2])
	p2 = Player.Player(temp[1].split("|")[1],temp[1].split("|")[2])
	
if int(p1.score) <= 0:
	print 'Location: http://students.washington.edu/zbadgerm/Math480/battlefield.cgi\n'
	
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>Battle Time!</title></head>

<body>

  <h3> The setup!</h3>
  
  <br/> 
  <p>You have <b>%s</b> ships left to place</p>
  <div id="puzzlearea">
"""%p1.score

#To place?
if (temp[0].strip() == me.strip()):
	print """
    <form method="post" action="set.cgi">
	<p>Place!: <input type="text" name="place"  maxlength="10" /></p>
	<input type='hidden' name='p2' value='%s' />
	<input type='hidden' name='score2' value='%s' />
	<input type='hidden' name='p1' value='%s' />
	<input type='hidden' name='score1' value='%s' />
	<input type="submit"/>
  </form>

	"""%(p2.position,p2.score,p1.position,p1.score)
else:
	print """
	<p>Waiting for opponent%s%s</p>
	"""%(str(me).strip(), str(temp[0]).strip())

print """
	
  <p>Your board<p>
  <div id="puzzlearea">
 """
 
for i in range(len(p1.position)):
	for j in range(len(p1.position[i])):
		print '<div class = "%s">'%("c" + str(p1.position[i][j]))
		print '%s%s</div>'%(i,j)
 
  

