import ugfx
import network
import time
import badge
import appglue
try:
    import usocket as socket
except:
    import socket
from struct import unpack

HOST = "sha2017.schaeffer.tk"
PORT = 2017
FONT = "PermanentMarker22"
FONTSIZE = 22

rank = -1
score = 0
total = 0

def print_msg(MSG):
    ugfx.string(0, 1, MSG, FONT, ugfx.BLACK)
    ugfx.flush()

def print_status():
    global rank
    global score
    global total
    global pkts_rcvd
    ugfx.clear(ugfx.WHITE)
    ugfx.string(0, 1*FONTSIZE,"Rank: %d"%(rank), FONT, ugfx.BLACK)
    ugfx.string(0, 2*FONTSIZE,"Score: %d"%(score), FONT, ugfx.BLACK)
    ugfx.string(0, 3*FONTSIZE,"total bytes: %d"%(total), FONT, ugfx.BLACK)
    ugfx.string(0, 4*FONTSIZE,"pkts recv: %d"%(pkts_rcvd), FONT, ugfx.BLACK)
    ugfx.flush()

def led(n, a):
    leds = []
    for i in range(n): leds += [a, 0, a, 0]
    for i in range(6-n): leds += [0, 0, 0, 0]
    badge.leds_send_data(bytes(leds))


def quit(pressed):
    if pressed:
        appglue.start_app("")

def btn_event(pressed):
    global nick
    global rank
    global score
    global total
    global npkt

    if not pressed: return
    badge.vibrator_activate(1)
    MESSAGE = bytearray(str(nick))
    if (npkt%70) >= 60:
        print_msg("JUMBO PACKET!")
        XTRA = bytearray("#"*1000)
        MESSAGE += XTRA
    sock.sendto(MESSAGE, remote_addr)
    npkt += 1

buttons = [ugfx.JOY_UP, ugfx.JOY_DOWN, ugfx.JOY_LEFT, ugfx.JOY_RIGHT,
    ugfx.BTN_SELECT, ugfx.BTN_START, ugfx.BTN_A, ugfx.BTN_B]

badge.init()
badge.eink_init()
ugfx.init()
ugfx.clear(ugfx.WHITE)
badge.leds_enable()

print_msg("config network")

sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.scan()
sta_if.connect("SHA2017-insecure")

ugfx.clear(ugfx.WHITE)
print_msg("connecting")

while not sta_if.isconnected():
    time.sleep(0.1)

#ugfx.set_lut(ugfx.LUT_FASTEST)

ugfx.input_init()
for button in buttons:
    ugfx.input_attach(button, btn_event)
ugfx.input_attach(ugfx.BTN_START, quit)

nick = badge.nvs_get_str("owner", "name", "NOBODY")
nick = (str(nick) + "_"*32)[:32]
ugfx.clear(ugfx.WHITE)
ugfx.string(0, 1, "Press button to", FONT, ugfx.BLACK)
ugfx.string(0, FONTSIZE, "waste bandwidth", FONT, ugfx.BLACK)
ugfx.flush()

local_addr = socket.getaddrinfo("0.0.0.0", PORT)[0][-1]
remote_addr = socket.getaddrinfo(HOST, PORT)[0][-1]
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(local_addr)
sock.settimeout(0)

led_uit = bytes(24)
led_aan = []
for i in range(6): led_aan += [0, 0, 16, 0]
led_aan = bytes(led_aan)

last_draw = 0
npkt = 0
pkts_rcvd = 0

while (True):
    try:
        data, addr = sock.recvfrom(1024)
    except:
        time.sleep(0.01)
        continue
    now = time.time()
    pkts_rcvd += 1
    if now - last_draw > .5:
        led((npkt%70)//10, 16)
        rank, score, total = unpack('!QQQ', data)
        #print_msg("PACKET!")
        #led(0, 16)
        print_status()
        last_draw = now