import cookielib, urllib2,urllib,random,time,sys,math

#peerbet login username and password (They will be echoed to the screen!)
username='yourusername'
password='yourpassword'


#numraffles: number of raffles to create
#max_lose: max losing streak before quitting
#satoshi: price of single ticket
#ret_ratio: return ratio
#buy_tickets: number of tickets to buy

#Examples:

#Thousand Mode (5000/10500)
#numraffles=10
#max_lose=9
#satoshi=2
#ret_ratio=2.1
#buy_tickets=5000

#Hundred Mode (50/105)
#numraffles=10
#max_lose=9
#satoshi=100
#ret_ratio=2.1
#buy_tickets=50

#100/110
#numraffles=20
#max_lose=2
#satoshi=100
#ret_ratio=1.1
#buy_tickets=100

#Set to 0 if you want to monitor old raffles
ignore=1


#price of single ticket after the first loss (FIXME)
#satoshi*=random.uniform(2, 3)
satoshidbl=satoshi

#not recommended to modify anything after this line

#Dont tread on me
args_num=len(sys.argv)

print 'args_num = ' + str(args_num)

#if args_num==1:
#    sys.exit()

sessionkey=str()

if args_num>1:
    if sys.argv[1] is not None: 
        sessionkey=str(sys.argv[1])
    

total_tickets=int(math.floor(float(ret_ratio)*float(buy_tickets)))
ticketpricebase=float(satoshi)/100000000
ticketpricedbl=float(satoshidbl)/100000000
stoppage=ticketpricebase*total_tickets

rlose_amt=ticketpricebase*float(buy_tickets)
#rwin_amt=(total_tickets-buy_tickets)*ticketpricebase
rwin_amt=ticketpricebase*float(total_tickets)
ticketprice=ticketpricebase
sell_tickets=total_tickets-buy_tickets

print 'Key: ' + str(sessionkey)
print 'Username: ' + str(username)
print 'password: ' + str(password)
print 'numraffles: ' + str(numraffles)
print 'max_lose: ' +  str(max_lose)
print 'satoshi: ' + str(satoshi)
print 'satoshidbl: ' + str(satoshidbl)
print 'ret_ratio: ' + str(ret_ratio)
print 'buy_tickets: ' + str(buy_tickets)
print 'sell_tickets: ' + str(sell_tickets)
print 'total_tickets: ' + str(total_tickets)
print 'ticketpricebase: ' + str('%.8f' % ticketpricebase)
print 'ticketpricedbl: ' + str('%.8f' % ticketpricedbl)
print 'total_tickets_price: ' + str('%.8f' % (float(total_tickets) * ticketpricebase))
print 'stoppage: ' + str('%.8f' % stoppage)
print 'rlose_amt: ' +  str('%.8f' % rlose_amt)
print 'rwin_amt: ' +  str('%.8f' % rwin_amt)
print 'ticketprice: ' + str('%.8f' % ticketprice)
print 'Win percentage: ' + str((float(buy_tickets)/float(total_tickets))*float(100))
print 'Lose percentage: ' + str((float(sell_tickets)/float(total_tickets))*float(100))
print 'Sleeping for 10 sec check the values, break if incorrect'
time.sleep(10)


cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

if args_num==1:
    params = urllib.urlencode({'username': str(username), 'password': str(password)})
    print "https://peerbet.org/api.php?method=login&%s" % params
    r = opener.open("https://peerbet.org/api.php?method=login&%s" % params)
    loginsession=r.read()
    print loginsession
    loginsession=eval(loginsession)
    sessionkey=str(loginsession['key'])
    
keyparam = urllib.urlencode({'key':sessionkey})

lose_count=0;

raffle_id_list = []
raffleid=0

lastmessageid=0

#Uncomment to allow getting my raffle count
"""
time.sleep(random.uniform(5, 7))
f = opener.open("https://peerbet.org/api.php?method=getmyrafflecount&%s" % keyparam)

rafflecount=f.read()
print rafflecount
rafflecount=eval(rafflecount)
print 'My Raffles Count:' + str(rafflecount['count'])

"""

#allow monitoring open raffles
myraffles=[]

if ignore==0:
    time.sleep(random.uniform(5, 7))
    params = urllib.urlencode({'key':sessionkey})
    print "https://peerbet.org/api.php?method=getmyraffles&%s" % params
    f = opener.open("https://peerbet.org/api.php?method=getmyraffles&%s" % params)
    rr=f.read()
    print rr
    myraffles=eval(rr)
    
    #status "open" - there are unsold tickets in the game, "waiting" - waiting for the next Bitcoin block, "win" - current user won the game, "lose" - current user lost the game, "finished" if the raffle is finished but current user did not participated
    
    for m in myraffles:
        if m['status']=='open':
            if m['tickets_total'] == str(total_tickets):
                raffle_id_list.append(m['raffle_id'])
    
    
    for raffleid in raffle_id_list:
        print 'Open raffle: ' + str(raffleid)
    
    print 'Total already open: ' + str(len(raffle_id_list))
    time.sleep(random.uniform(2, 3))
    

totalLoss=0
totalWin=0



while True:

    params = urllib.urlencode({'key':sessionkey})
    print "https://peerbet.org/api.php?method=getuserinfo&%s" % params
    f = opener.open("https://peerbet.org/api.php?method=getuserinfo&%s" % params)
    userinfo=f.read()
    print userinfo
    userinfo=eval(userinfo)
    balance=float(userinfo['balance'])
    
    print 'balance: ' + str('%.8f' %  balance)

    if lose_count>=max_lose:
        print 'lose count greater than max lose'
        break
    
    if stoppage>=balance:        
        print 'stoppage greater than balance'
        break
    else:
        #params = urllib.urlencode({'key':sessionkey, 'tickets': total_tickets, 'price': ticketprice,'expire':'1','password':'rafpassword','instant':'1'})
        #for x in range(0, 3):
        while len(raffle_id_list) < numraffles:
            #time.sleep(random.uniform(60*60, 2*60*60))
            sleeptime=random.uniform(5, 10)
            print 'sleeping for ' + str(sleeptime)
            time.sleep(sleeptime)

            print 'Create new Raffle'
            params = urllib.urlencode({'key':sessionkey, 'tickets': str(total_tickets), 'price': str('%.8f' % ticketprice),'instant':'0'})
            print 'https://peerbet.org/api.php?method=createraffle&%s' % params
            raffle=opener.open('https://peerbet.org/api.php?method=createraffle&%s' % params)
            raf= raffle.read()
            print raf
            raf=eval(raf)
            raffleid=raf['raffle_id']
            raffle_id_list.append(raffleid)

            print 'Buy tickets in new Raffle'
            params = urllib.urlencode({'key':sessionkey, 'raffle': raffleid, 'tickets': buy_tickets})
            print 'https://peerbet.org/api.php?method=buytickets&%s' % params
            bought=opener.open('https://peerbet.org/api.php?method=buytickets&%s' % params)
            bou=bought.read()
            print bou
            balance=balance-rlose_amt
            print 'balance: ' + str('%.8f' %  balance)
            ticketprice=ticketpricebase
            #bou=eval(bou)


        while len(raffle_id_list) >= numraffles:
            temp_raffle_list=[]
            for raffleid in raffle_id_list:
                temp_raffle_list.append(raffleid)

            for raffleid in temp_raffle_list:
                time.sleep(random.uniform(5, 7))
                params = urllib.urlencode({'key':sessionkey, 'raffle': raffleid})
                print 'https://peerbet.org/api.php?method=getraffleinfo&%s' % params
                f=opener.open('https://peerbet.org/api.php?method=getraffleinfo&%s' % params)
                raffle=f.read()
                print raffle
                raffle=eval(raffle)

                print 'Raffle Id: ' + str(raffle['raffle_id']) + ' Ticket price: ' + str(raffle['ticket_price']) + ' Tickets Total: ' + str(raffle['tickets_total']) + ' Tickets Sold: ' + str(raffle['tickets_sold']) + ' My Tickets: ' + str(raffle['my_tickets_count']) + ' My List: ' + str(raffle['my_ticket_list']) + ' Status: ' + str(raffle['status']) 

                if raffle['status']=='win':
                    ticketprice=ticketpricebase
                    lose_count=0
                    totalWin+=1
                    print 'Win! Winning ticket: ' + str(raffle['winning_ticket'])
                    balance=balance+rwin_amt
                    raffle_id_list.remove(raffleid)
                elif raffle['status']=='lose':
                    if lose_count==0:
                        ticketprice=ticketpricedbl
                    else:
                        ticketprice=ticketpricebase
                    lose_count+=1
                    totalLoss+=1
                    print 'Lose! Winning ticket: ' + str(raffle['winning_ticket'])
                    raffle_id_list.remove(raffleid)
                elif raffle['status']=='finished':
                    raffle_id_list.remove(raffleid)
                elif raffle['status']=='waiting':
                    raffle_id_list.remove(raffleid)


            winB=((float(totalWin)*rwin_amt)-(float(totalWin)*rlose_amt))
            loseB=float(totalLoss)*rlose_amt
            diffB=winB-loseB
            totPlayed=totalLoss+totalWin

            print 'Balance: ' + str('%.8f' % balance) + ' Lose Count : ' + str(lose_count) + ' TotalWin : ' + str(totalWin) + ' (' + str('%.8f' % winB) + ') TotalLoss : ' + str(totalLoss) + ' (' + str('%.8f' % loseB) + ') Diff (' + str('%.8f' % diffB) + ') Open tickets ' + str(len(raffle_id_list)) 
            if totPlayed>0:
                print 'Percentage Win : ' + str((float(totalWin)/float(totPlayed))*float(100))
                print 'Percentage Lose: ' + str((float(totalLoss)/float(totPlayed))*float(100))
            else:
                print 'Percentage: Undefined'
            print 'Balance in game: ' + str('%.8f' % (float(len(raffle_id_list))*rlose_amt))

            """
            if lastmessageid == 0:
                params = urllib.urlencode({'key':sessionkey})
            else:
                params = urllib.urlencode({'key':sessionkey, 'lastmessageid': lastmessageid})

            print "https://peerbet.org/api.php?method=getchatmessages&%s" % params
            f = opener.open("https://peerbet.org/api.php?method=getchatmessages&%s" % params)
            chat=f.read()
            chat=eval(chat)
            chat=chat['message_list']
            chat=eval(chat)
            
            #status "open" - there are unsold tickets in the game, "waiting" - waiting for the next Bitcoin block, "win" - current user won the game, "lose" - current user lost the game, "finished" if the raffle is finished but current user did not participated
            
            for c in chat:
                lastmessageid=c['message_id'] 
                print c['bot'] + ' ' + c['posted_by'] + ':' + c['message_body']
            """ 

            if len(raffle_id_list) >= numraffles:
                sleeptime=random.uniform(60, 2*60)
                print 'Waiting ' + str(sleeptime) + 's ...'
                time.sleep(sleeptime)
            else:
                sleeptime=random.uniform(10, 30)
                print 'Waiting ' + str(sleeptime) + 's ...'
                time.sleep(sleeptime)
 
