import badge
import ugfx
import time
import deepsleep
ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()

nick = badge.nvs_get_str("owner", "name", "")

badge.init()
ugfx.init()
ugfx.input_init()
badge.leds_init()
badge.leds_enable()

def home(pressed):
  if pressed:
    deepsleep.reboot()

def bright_up(pressed):
  global brightness
  if pressed:
    brightness += 0.1
    if brightness > 1: brightness = 1

def bright_down(pressed):
  global brightness
  if pressed:
    brightness -= 0.1
    if brightness < 0: brightness = 0

def speed_up(pressed):
  global speed
  if pressed:
    speed += 0.02
    if speed > 0.166666: speed = 0.166666

def speed_down(pressed):
  global speed
  if pressed:
    speed -= 0.02
    if speed < 0.01: speed = 0.01

brightness = 0.5
speed = 0.05 

def hsv_to_rgb(h, s, v):
    if s == 0.0: return (v, v, v)
    i = int(h*6.) # XXX assume int() truncates!
    f = (h*6.)-i; p,q,t = v*(1.-s), v*(1.-s*f), v*(1.-s*(1.-f)); i%=6
    if i == 0: return (v, t, p)
    if i == 1: return (q, v, p)
    if i == 2: return (p, v, t)
    if i == 3: return (p, q, v)
    if i == 4: return (t, p, v)
    if i == 5: return (v, p, q)

ugfx.input_attach(ugfx.BTN_START, home)
ugfx.input_attach(ugfx.JOY_UP, bright_up)
ugfx.input_attach(ugfx.JOY_DOWN, bright_down)
ugfx.input_attach(ugfx.JOY_LEFT, speed_down)
ugfx.input_attach(ugfx.JOY_RIGHT, speed_up)

leds_array = bytes(24)
def set(i):
	global brightness
	global speed
	result = b""
	for j in range(6):
		color = (i + speed * j) % 1
		r, g, b = hsv_to_rgb(color, 1, brightness)
		result += bytes([int(r * 255), int(g * 255), int(b * 255), 0])
	badge.leds_send_data(result)

ugfx.string_box(0,10,296,26, "STILL", "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)
ugfx.string_box(0,45,296,38, nick, "PermanentMarker36", ugfx.BLACK, ugfx.justifyCenter)
ugfx.string_box(0,94,296,26, "Anyway", "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyCenter)

#the line under the text
str_len = ugfx.get_string_width(nick,"PermanentMarker36")
line_begin = int((296-str_len)/2)
line_end = str_len+line_begin
ugfx.line(line_begin, 83, line_end, 83, ugfx.BLACK)

#the cursor past the text
cursor_pos = line_end+5
ugfx.line(cursor_pos, 46, cursor_pos, 81, ugfx.BLACK)

ugfx.flush(ugfx.LUT_FULL)

i = 0
while True:
	set(i)
	time.sleep(0.05)
	i += speed
	i = i % 1