from bokeh.plotting import figure, curdoc
from bokeh.models import Button
from bokeh.layouts import column
import pang
from threading import Thread
import pickle as pkl

pong_game = pang.AIPong(debug=True)
doc = curdoc()
f = figure(plot_width=500, plot_height=500,x_range=[0,1],y_range=[0,1],tools="")
f.xgrid.grid_line_color = None
f.ygrid.grid_line_color = None
f.axis.visible=False
ball = f.circle([0.5],[0.5],size=10)
puck = f.line([1, 1], [0.5-0.05, 0.5+0.05], line_width=5)

def update():
    if not pong_game.game.dead:
        x = pong_game.game.ball.x_pos
        y = pong_game.game.ball.y_pos
        puck_y = pong_game.game.get_right_puck_position()
        puck_len = pong_game.game.get_right_puck_length()
        print pong_game.game.get_ball_cell(), pong_game.game.get_right_puck_cell()
        print x,y 
        ball.data_source.data["y"] = [y]
        ball.data_source.data["x"] = [x]
        puck.data_source.data["y"] = [puck_y-0.05, puck_y+0.05]

def start():
    global pong_game
    ball.data_source.data["y"] = [0.5]
    ball.data_source.data["x"] = [0.5]
    puck.data_source.data["y"] = [0.5-0.05, 0.5+0.05]
    pong_game = pong_game = pang.AIPong(debug=True)
    weights = pkl.load(open("endweights.pkl", "r"))
    for neuron in range(pong_game.network.no_neurons):
        pong_game.network.set_weights(weights[neuron], neuron)
    t = Thread(target=pong_game.run_games)
    t.start()

doc.add_periodic_callback(update, 10)
button = Button(label="Start")
button.on_click(start)
doc.add_root(column(button, f))

