import ugfx, badge,time
import binascii
import easyrtc
from random import randint

def hex_to_rgb_tuple(hex_str):
    r,g,b = binascii.unhexlify(hex_str)
    return (g,r,b)

# GLOBALS
led = 0
nick = badge.nvs_get_str("owner","name", "")

white = hex_to_rgb_tuple("ffffff")
off = hex_to_rgb_tuple("000000")

def clear_ghosting():
	ugfx.clear(ugfx.BLACK)
	ugfx.flush()
	badge.eink_busy_wait()
	ugfx.clear(ugfx.WHITE)
	ugfx.flush()
	badge.eink_busy_wait()

badge.init()
ugfx.init()
ugfx.LUT_FULL
ugfx.input_init()

badge.leds_init()

def go_home(pushed):
    if(pushed):
        import machine
        machine.deepsleep(1)

def up_pushed(pushed):
	print("up")
	if(pushed):
		led_rainbow()

def down_pushed(pushed):
	print("down")
	if(pushed):
		display_troll()

def left_pushed(pushed):
	print("left")
	if(pushed):
		buzz()

def right_pushed(pushed):
	print("right")
	if(pushed):
		display_clock()

def re_draw():
	print("redraw")

def led_rainbow():
	count = 0
	leds_array = bytes(24)
	badge.leds_enable()
	while (count < 50):
		print("Counter: %d" % (count))
		#ugfx.string_box(0,60,296,26, "counter: " + str(count), "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyLeft)
		badge.leds_send_data(leds_array)
		#ugfx.flush()
		time.sleep(0.1)
		leds_array = leds_array[4:] + bytes([randint(128, 255), randint(0, 255), randint(0, 128), 0])
		badge.leds_send_data(leds_array)
		time.sleep(0.1)
		leds_array = leds_array[4:] + bytes([randint(0, 128), randint(0, 255), randint(128, 255), 0])
		count = count + 1
		time.sleep(0.1)
	badge.leds_disable()

def display_troll():
	clear_ghosting()
	ugfx.string_box(0,10,296,26, "still hacking anyway", "Roboto_BlackItalic20", ugfx.BLACK, ugfx.justifyLeft)
	ugfx.string_box(0,40,296,26, nick, "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyLeft)
	badge.eink_png(180,10,'/lib/just_testing/logo.png')
	ugfx.flush()

def buzz():
	    badge.vibrator_activate(0xFF)

def display_clock():
	t = easyrtc.string()
	ugfx.string_box(0,80,296,26, t, "Roboto_BlackItalic20", ugfx.BLACK, ugfx.justifyLeft)
	ugfx.flush()

def show_colours(colours):
    allcolours = ''.join([''.join(["{0:02x}".format(int(x)) for x in [r,g,b,0]]) for (r,g,b) in colours])
    badge.leds_send_data(binascii.unhexlify(allcolours), 24)

	
def led_flash():
	count = 0
	badge.leds_enable()
	while(count < 5):
		show_colours(white)
		time.sleep(0.05)
		show_colours(off)
		time.sleep(0.05)
		count = count + 1


display_troll()

ugfx.input_attach(ugfx.BTN_A, display_troll)
ugfx.input_attach(ugfx.BTN_B, led_flash)
ugfx.input_attach(ugfx.BTN_START, go_home)
ugfx.input_attach(ugfx.BTN_SELECT, go_home)
ugfx.input_attach(ugfx.JOY_UP, up_pushed)
ugfx.input_attach(ugfx.JOY_DOWN, down_pushed)
ugfx.input_attach(ugfx.JOY_LEFT, left_pushed)
ugfx.input_attach(ugfx.JOY_RIGHT, right_pushed)