import time
import wifi
import network
import usocket
import appglue
import freedomgfx as fgfx

def clear_screen(color):
    fgfx.area(0,0,296,128, color)
    fgfx.flush()

def show_animation(animation):
    print(animation)
    com_socket.sendall(animation+"\n")
    fgfx.area(200, 100, 100, 24, fgfx.WHITE)
    fgfx.string(200, 100, animation, "Roboto_BlackItalic24",fgfx.BLACK)
    fgfx.flush()


fgfx.init()
fgfx.input_init()
fgfx.input_attach(fgfx.BTN_SELECT, lambda pressed: appglue.home())

#ugfx.clear(ugfx.WHITE)
fgfx.string(10, 10, "Still wating for wifi... aniway","Robot_Regular12", fgfx.BLACK)
fgfx.flush()

wifi.init()

sta_if = network.WLAN(network.STA_IF)
sta_if.connect("FrankenFellowshipFSFE")
while not wifi.sta_if.isconnected():
    time.sleep(0.1)
    fgfx.poll()
    pass

fgfx.string(10, 20, "Connected to wifi","Robot_Regular12", fgfx.BLACK)
fgfx.flush() 

fgfx.string(10, 30, "listen to server address","Robot_Regular12", fgfx.BLACK)
fgfx.flush()

listen_socket = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)
udp_addr = ("255.255.255.255", 60000)
listen_socket.bind(udp_addr)

server_addr = ''

while True:
    data, addr = listen_socket.recvfrom(2048)
    if "plussyDisplay" in data.decode():
        server_addr = addr[0]
        break

fgfx.string(10, 40, "server address is " + server_addr,"Robot_Regular12", fgfx.BLACK)
fgfx.string(10, 50, "connecting to server", "Robot_Regular12", fgfx.BLACK)
fgfx.flush()

com_socket = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
com_socket.connect((server_addr, 60000))

clear_screen(fgfx.WHITE)
fgfx.flush()

## actuall ctrl shit starts here
fgfx.string(10,25,"PRESS ARROW KEYS","Roboto_BlackItalic24",fgfx.BLACK)
fgfx.string(10,50,"FOR CHANGING","Roboto_BlackItalic24",fgfx.BLACK)
fgfx.string(10,75,"ANIMATION","Roboto_BlackItalic24",fgfx.BLACK)
fgfx.flush()

fgfx.input_attach(fgfx.JOY_UP, lambda pressed: show_animation("a00"))
fgfx.input_attach(fgfx.JOY_RIGHT, lambda pressed: show_animation("a01"))
fgfx.input_attach(fgfx.JOY_DOWN, lambda pressed: show_animation("a02"))

while True:
    fgfx.poll()
    time.sleep(0.1)