import urllib2
import threading
import time
import random
import sys

path = 'http://localhost:8081/sessionrig/customerror'
#path = 'http://localhost:8080/sessionrig'

entry = path + '/entry'
read = path + '/read'
write = path + '/write'
slowWrite = path + '/write?nap:float=0.1'
error = path + '/error'
sessionless = path + '/sessionless'

def pickUrl():
    return random.choice([read, write, slowWrite, error, sessionless])
    #return random.choice([write, error])


def openUrl(url, cookie, note):    
    request = urllib2.Request(url)
    if cookie:
        request.add_header('Cookie',cookie)
    try:
        response = urllib2.urlopen(request)
        body = response.read()
        if cookie and 'no session data' in body:
            print 'no session data', url, cookie, note
        setcookie = response.headers.get('Set-Cookie',None)
        if setcookie:
            cookie = setcookie.split(';')[0]
            #print 'cookie:', cookie, note
    except urllib2.HTTPError, response:
        #print response
        body = response.read()
        if cookie and 'no session data' in body:
            print 'no session data', url, cookie, note
        if 'KeyError' in body:
            print (time.ctime(time.time()), response, url, note, 'body:', body)
    except urllib2.URLError, error:
        print error
    return cookie


class DetachedRequest(threading.Thread):
    def __init__(self, url, cookie, note):
        self.url = url
        self.cookie = cookie
        self.note = note
        threading.Thread.__init__(self)
    def run(self):
        begin = time.time()
        time.sleep(random.uniform(0,0.25))
        self.note['detachedSleepfor'] = time.time() - begin
        openUrl(self.url, self.cookie, self.note)

    
class Browser(threading.Thread):

    def __init__(self, sleepiness, sessionLength, browserThreads):
        self.sleepiness = sleepiness
        self.sessionLength = sessionLength
        self.browserThreads = browserThreads
        threading.Thread.__init__(self)

    def run(self):
        while True:
            # Each loop simulates a browser session - several page requests
            # using the same Cookie.
            url = entry
            sleepfor = 0
            cookie = None
            
            for page in range(random.randint(1, self.sessionLength)):
                # Each loop simulates a page request for the current session.
                note = {'sleepiness':self.sleepiness,
                        'sleepfor':sleepfor}
                cookie = openUrl(url, cookie, note)

                # Simulate browser fetching other http content refered to
                # in the last received content.
                for reference in range(random.randint(0,self.browserThreads)):
                    DetachedRequest(pickUrl(), cookie, note).start()

                # Sleep for a bit. Remembing just how long we intented to sleep
                # for so that we can report this if needed.
                begin = time.time()
                time.sleep(random.uniform(0, self.sleepiness))
                sleepfor = time.time() - begin
                url = pickUrl()



def start(browserCount, sleepiness, sessionLength=1000, browserThreads=4):
    for browser in range(browserCount):
        Browser(sleepiness, sessionLength, browserThreads).start()

# Kick off a mini colony of robots. With a range of sleepiness.
#start(50,400)
#start(50,200)
#start(50,100)
#start(50,50)
start(20,30,1000,0)
