

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 = []
	winnertake = 0.99 # amount the winner gets of nominal bet
	houseaccount = -1 # id of house account

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)))
        return render.index(payout(int(name)))

# APPLICATION-SPECIFIC

# Payout determines whom to pay and how much
# If true, then proposer is paid whatever  the taker bets and taker loses that
# amount. If false, then taker gets what taker bets/(moneyline/100).
def payout(betid):
 con = lite.connect('bet.db')
 with con:    
  cur = con.cursor()    
  # x = "BEGIN TRANSACTION"
  # cur.execute(x)
  flag_moneyline_user = evalpred(cur, betid)
  totaltoproposer = 0
  x = "SELECT userid, amount FROM bettaken  WHERE betid = '" + str(betid)  + "'"
  cur.execute(x)
  rows = cur.fetchall()
  # It would be better to do this as one massive join, but can't do this
  # in sqlite. We would join bettaken and account to update account.balance
  # based on all the users..
  # Something like an update that joins with bettaken
  # 
  # This is how how the r[1] field (the moneyline) works:
  # If the person taking the bet, bets say $100 and the moneyline is 300,
  # then the taker gets $100/3 as a winning.
  # If the moneyline is say -400, then the taker gets $400 as a winning.
  # Whatever proposer pays, the proposer pays an additional rake to the house.
  # If the taker loses, then taker loses $100 + rake * $100.
  for r in rows:
	if flag_moneyline_user[0]:
		amt = int(r[1])
		totaltoproposer+= amt
		x = "UPDATE account SET balance= balance - " + str(amt) + " WHERE userid = " + str(r[0])
		cur.execute(x)
	else:
		print "r[1] is: ", r[1]
		print "flag_moneyline_user[1] is: ", flag_moneyline_user[1]
		amt = int(r[1])
		if amt > 100:
		  amt = (0.0 + (amt * 100))/float(flag_moneyline_user[1])
		  # proposer pays out less by this factor.
		elif amt < -100:
		  amt = (0.0 + (amt * abs(float(flag_moneyline_user[1]))))/100
		  # proposer pays out more by the absolute value of this
		totaltoproposer-= amt
		x = "UPDATE account SET balance= balance + " + str(Constants.winnertake * amt) + " WHERE userid = " + str(r[0])
		print "x is: ", x
		cur.execute(x)
  # pay off or take money from proposer
  if totaltoproposer > 0:
  	x = "UPDATE account SET balance= balance + " + str(Constants.winnertake * totaltoproposer) + " WHERE userid = " + str(flag_moneyline_user[2])
  	cur.execute(x)
  else:
  	x = "UPDATE account SET balance= balance + " + str(totaltoproposer) + " WHERE userid = " + str(flag_moneyline_user[2])
  	cur.execute(x)
  x = "UPDATE account SET balance= balance + " + str((1.0-Constants.winnertake) * abs(totaltoproposer)) + " WHERE userid = " + str(Constants.houseaccount)
  print "updating house account: ", x
  cur.execute(x)
  # x = "END TRANSACTION"
  # cur.execute(x)
  return generatefromaccount(cur)
  
  
   

# see whether the proposer of the bet won or lost
def evalpred(cur, betid):
       x = "SELECT gameid, predicatestring, minnumpreds, moneyline, proposerid 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 [True, r[3], r[4]]
       else:
          return [False, r[3], r[4]]

         

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


def generatefromaccount(cur):
       out = 'generating an output for all accounts '
       x = "SELECT * FROM account " 
       print x
       cur.execute(x)
       rows = cur.fetchall()
       for row in rows[:3]:
          out+= ' ID: '+ str(row[0])+ ' balance: '+ str(row[1]) + ' First name: '+ str(row[3]) + ' Second name: ' + row[4]  + '<br>'
       return out

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()




