

import datetime
import sqlite3 as lite
import sys
import web, random

# APPLICATION-SPECIFIC




urls = ( '/(.*)', 'index', '/bet','bet_server')

# relates after the url /xxx to the server that should be called.

# What does this template.render thing. 
render = web.template.render('templates')


class Constants:
	x = 10
	users = {}
	colors = ['red','blue','green']
	bet_messages = []

count = 0
lastx = ""

# call with /?name=Joe
class index:
    def GET(self,name):
        # return render.index(name)
        # return render.index(generatefromdb(name))
        return render.index(evalpred(int(name)))

# APPLICATION-SPECIFIC

# see whether the proposer of the bet won or lost
def evalpred(betid):
   con = lite.connect('bet.db')
   with con:    
       cur = con.cursor()    
       x = "SELECT gameid, predicatestring, minnumpreds FROM betdescription  WHERE betid = '" + str(betid)  + "'"
       cur.execute(x)
       rows = cur.fetchall()
       r = rows[0] # Should be only one row
       preds = r[1].split(";")
       mycount = 0
       for p in preds:
	  predparts = (p.strip()).split(" ")
	  x = "SELECT player, stattype, numvalue FROM result WHERE gameid = " +  str(r[0]) + " and player = '" + predparts[0] + "' and stattype = '" + predparts[1] + "'"
	  print x
	  cur.execute(x)
       	  pr = (cur.fetchall())[0] # Should be only one row
	  if (predparts[2] == "=")  and (int(pr[2]) == int(predparts[3])):
		mycount+= 1
	  if (predparts[2] == ">")  and (int(pr[2]) > int(predparts[3])):
		mycount+= 1
	  if (predparts[2] == "<")  and (int(pr[2]) < int(predparts[3])):
		mycount+= 1
	  print "mycount is ", mycount
     
       if  mycount >= int(str(r[2])):
          return 'PREDICATE ' + r[1] + ' with threshold ' + str(r[2]) + ' SUCCEEDS'
       else:
          return 'PREDICATE ' + r[1] + ' with threshold ' + str(r[2]) + ' FAILS ENTIRELY'

         

# change balances for a betid based on who wins and the odds and amount bet
def adjustbalance(betid):
	return betid



def generatefromdb(name):
   global count
   out = 'generating an output for ' + name + ' with count: ' + str(count)
   count+= 1
   con = lite.connect('bet.db')
   with con:    
       cur = con.cursor()    
       x = "SELECT * FROM game WHERE team1 = '" + name + "' OR team2 = '" + name + "'"
       print x
       cur.execute(x)
   
       rows = cur.fetchall()
   
       for row in rows[:3]:
          out+= ' Game: '+ str(row[0])+ ' start date: '+ str(row[1]) + ' start time: '+ str(row[2]) + ' location: ' + row[3]  + ' team: ' + row[4] + ' other team: ' + row[5] + ' game type: ' + row[7] + '<br>'

   return out


if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()




