import pyNetLogo
import pprint, time

def turtles_created(new_turtles):
    for turtle_idx in set(new_turtles.keys()) - set(turtles.keys()):
        print "Turtle %i created." % turtle_idx

def turtles_deleted(new_turtles):
    for turtle_idx in set(turtles.keys()) - set(new_turtles.keys()):
        print "Turtle %i deleted." % turtle_idx

link = pyNetLogo.NetLogoLink(gui=False,
                             netlogo_home="C:\\Program Files\\NetLogo 6.0.3",
                             netlogo_version="6")

turtles = {}
link.load_model('BouncingBalls.nlogo')
link.command("setup")
print "Ready to go..."
print link.report("reflection:turtles")
state = "paused"
to_setup = False
ignored_attributes = set(["WHO", "HEADING", "SHAPE", "LABEL", "LABEL-COLOR", "BREED", "HIDDEN?", "PEN-SIZE", "PEN-MODE"])

def user_inputter():
    global state
    global to_setup
    while 1:
        cmd = raw_input()
        if cmd == "reset":
            to_setup = True
        elif cmd == "step":
            state = "stepping"
        elif cmd == "continuous":
            state = "continuous"
        elif cmd == "pause":
            state = "paused"
        else:
            print "invalid command %s" % cmd

import threading
thrd = threading.Thread(target=user_inputter)
thrd.start()

while 1:
    if state in ["stepping", "continuous"]:
        start_time = time.time()
        link.command("go")
        #attr_names = [attr_name for attr_name in link.report('last last reflection:breeds') if attr_name not in ["WHO", "HEADING", "SHAPE", "LABEL", "LABEL-COLOR", "BREED", "HIDDEN?", "PEN-SIZE", "PEN-MODE"]]
        #new_turtles = {int(turtle_id): {attr_name: str(link.report('[' + attr_name + '] of turtle ' + str(turtle_id))) for attr_name in attr_names} for turtle_id in link.report('[who] of turtles')}
        attr_names = link.report('last last reflection:breeds')
        all_turtle_attributes = link.report("reflection:turtles")
        new_turtles = {}
        for turtle_attributes in all_turtle_attributes:
            the_turtle = dict(zip(attr_names, turtle_attributes.getResultAsObject()))
            new_turtles[int(float(the_turtle["WHO"]))] = the_turtle
        new_turtles = {k: {ak: av for ak, av in new_turtles[k].iteritems() if ak not in ignored_attributes} for k in new_turtles.keys()}
        turtles_created(new_turtles)
        turtles_deleted(new_turtles)
        turtles = new_turtles
        pprint.pprint(new_turtles)
        if state == "stepping":
            state = "paused"
        print time.time() - start_time
    if to_setup:            
        link.command("setup")
        to_setup = False
print "Done"