import badge
import ugfx
import appglue
import socket
import wifi
import easydraw
import woezel
import easywifi
from time import sleep
import urequests as requests

rev = "rev. 56"
UDP_PORT = 5555
player = ""

def get_host():
    data = requests.get('https://derchris.eu/host.txt')
    UDP_HOST = data.text

    return UDP_HOST

def check_wifi():
    easywifi.enable(True)
    if easywifi.state==False:
        easydraw.msg("Meh unable to connect to network","FAILURE")
        easydraw.msg("Waiting 5 seconds to try again!")
        badge.eink_busy_wait()
        import machine
        machine.deepsleep(5000)

def check_update():
    easydraw.msg("Checking for updates", "Still Updating Anyway...", True)
    try:
        woezel.install('pong_controller')
        easydraw.msg("Updated! Rebooting now!")
        badge.nvs_set_str('boot','splash','pong_controller')
        badge.eink_busy_wait()
        import machine
        machine.deepsleep(1)
    except:
        easydraw.msg("No update available. Starting app!")
        badge.nvs_set_str('boot','splash','splash')

def home(pushed):
    if(pushed):
        print("go home")
        appglue.home()

def reset(pushed):
    global player
    if((pushed) and (player)):
        print("reset", player)
        command = "none"
        sendCommand(s, player, command)
        player = ""
        clean()
        screen(player)
        ugfx.flush()
        badge.leds_disable()

def player1(pushed):
    global player
    if((pushed) and not (player)):
        print("join game as player1")
        command = "left"
        player = "player1"
        clean()
        screen("Player 1")
        ugfx.flush()
        badge.leds_enable()
        badge.leds_send_data(bytes([0, 5, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0]))
        sendCommand(s, player, command)
    elif((pushed) and player == 'player1'):
        print("re-join games as player1")
        command = "left"
        player = "player1"
        sendCommand(s, player, command)
    else:
        print("game already joined")

def player2(pushed):
    global player
    if((pushed) and not (player)):
        print("join game as player2")
        command = "left"
        player = "player2"
        clean()
        screen("Player 2")
        ugfx.flush()
        badge.leds_enable()
        badge.leds_send_data(bytes([5, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0, 0]))
        sendCommand(s, player, command)
    elif((pushed) and player == 'player2'):
        print("re-join games as player2")
        command = "left"
        player = "player2"
        sendCommand(s, player, command)
    else:
        print("game already joined")

def up(pushed):
    if((pushed) and (player)):
        print(player, "up")
        command = "down"
        sendCommand(s, player, command)
        sleep(.2)
        sendCommand(s, player, "none")
    else:
        print("player not set")

def down(pushed):
    if((pushed) and (player)):
        print(player, "down")
        command = "up"
        sendCommand(s, player, command)
        sleep(.2)
        sendCommand(s, player, "none")
    else:
        print("player not set")

def left(pushed):
    global player
    if((pushed) and (player)):
        print(player, "left")
        command = "left"
        sendCommand(s, player, command)
    else:
        print("player not set")

def right(pushed):
    global player
    if((pushed) and (player)):
        print(player, "right")
        command = "none"
        sendCommand(s, player, command)
	player = ""
        clean()
        screen(player)
        ugfx.flush()
        badge.leds_disable()
    else:
        print("player not set")

def sendCommand(s, player_id, command):
    s.sendto(bytearray([ord(x) for x in player_id] + [ord(" ")] + [ord(x) for x in command.upper()]), (UDP_HOST,UDP_PORT))

def clean():
    ugfx.clear(ugfx.BLACK)
    ugfx.flush()
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()

def screen(player_name):
    ugfx.string(10, 5, "Host: " + UDP_HOST, "Roboto_Regular12",ugfx.BLACK)
    ugfx.string(50, 20, player_name ,"Roboto_Regular16",ugfx.BLACK)
    ugfx.string(190,25,"STILL","Roboto_BlackItalic24",ugfx.BLACK)
    ugfx.string(190,50,"Pong","PermanentMarker22",ugfx.BLACK)
    len = ugfx.get_string_width("Pong","PermanentMarker22")
    ugfx.line(190, 72, 204 + len, 72, ugfx.BLACK)
    ugfx.line(200 + len, 52, 200 + len, 70, ugfx.BLACK)
    ugfx.string(180,75,"Anyway","Roboto_BlackItalic24",ugfx.BLACK)
    ugfx.string(10, 110, "SELECT: exit, START: reset, A: P1, B: P2, U/D","Roboto_Regular12",ugfx.BLACK)
    ugfx.string(255, 115, rev ,"Roboto_Regular12",ugfx.BLACK)
    try:
        badge.eink_png(10,40,'/lib/pong_controller/shrug.png')
    except:
        ugfx.string(30,50,"Error loading shrug.png","Roboto_Regular16",ugfx.BLACK)

badge.init()
badge.leds_init()
ugfx.init()
ugfx.input_init()
ugfx.set_lut(ugfx.LUT_NORMAL)
clean()
check_wifi()
clean()
check_update()
clean()
UDP_HOST = get_host()
screen(player)
ugfx.flush()

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

ugfx.input_attach(ugfx.BTN_SELECT, home)
ugfx.input_attach(ugfx.BTN_START, reset)
ugfx.input_attach(ugfx.BTN_A, player1)
ugfx.input_attach(ugfx.BTN_B, player2)
ugfx.input_attach(ugfx.JOY_UP, up)
ugfx.input_attach(ugfx.JOY_DOWN, down)
#ugfx.input_attach(ugfx.JOY_LEFT, left)
#ugfx.input_attach(ugfx.JOY_RIGHT, right)

