import urllib
import json

ip_address = "127.0.0.1"
port = "5000"

lastGet = 0
lastSend = 0

creatureList = []

def getData():
    global lastGet, creatureList
    # only fetch new data once per second
    if millis() > lastGet + 1000:
        creatureList = []
        lastGet = millis()
        response = urllib.urlopen("http://"+ip_address+":"+port+"/get")
        j = json.load(response)
        print(j)
        c = []
        for c in j:
            c["x"] = int(c["x"])
            c["y"] = int(c["y"])
            c["color"] = unhex(c["color"])
            c["size"] = int(c["size"])
            creatureList.append(c)
    return creatureList

def sendData(myCreature):
    global lastSend
    # only send once per second    
    if millis() > lastSend + 1000:
        lastSend = millis()
        variableString = "name=" + myCreature["name"]
        variableString += "&x=" + str(myCreature["x"])
        variableString += "&y=" + str(myCreature["y"])
        variableString += "&color=" + hex(myCreature["color"])
        variableString += "&size=" + str(myCreature["size"])
        returnValue = loadStrings("http://"+ip_address+":"+port+"/move?" + variableString)