# Attention this is a custom version of the pretty clock app
# Pretty clock
# just to annoy Tom because i can't be bothered to do a pull request
# added red instead of ugly white color, and brightness control

import time, ntp, rgb, wifi, buttons, defines, system, machine
from default_icons import animation_connecting_wifi, icon_no_wifi

direction = 0
brightness = rgb.getbrightness()
rgb.clear()

if not wifi.status():
    data, size, frames = animation_connecting_wifi
    rgb.clear()
    rgb.framerate(3)
    rgb.gif(data, (12, 0), size, frames)
    wifi.connect()
    if wifi.wait():
        rgb.clear()
        rgb.framerate(20)
    else:
        print('No wifi')
        rgb.clear()
        rgb.framerate(20)
        data, frames = icon_no_wifi
        rgb.image(data, (12, 0), (8,8))
        time.sleep(3)
        rgb.clear()

if not wifi.status():
    print("Error connecting to wifi")
    system.reboot()

if not ntp.set_NTP_time():
    print("Error setting time")
    system.reboot()

wifi.disconnect()

UP, DOWN, LEFT, RIGHT = defines.BTN_UP, defines.BTN_DOWN, defines.BTN_LEFT, defines.BTN_RIGHT
A, B = defines.BTN_A, defines.BTN_B

def input_up(pressed):
    global direction
    direction = UP

def input_down(pressed):
    global direction
    direction = DOWN

def input_left(pressed):
    global direction
    direction = LEFT

def input_right(pressed):
    global direction
    direction = RIGHT

def input_B(pressed):
    global direction
    direction = B
	
def input_A(pressed):
    global direction
    direction = A

buttons.register(UP, input_up)
buttons.register(DOWN, input_down)
buttons.register(LEFT, input_left)
buttons.register(RIGHT, input_right)
buttons.register(B, input_B)
buttons.register(A, input_B)

tmold = 70
rgb.background((0,0,0))
rgb.clear()
rgb.framerate(1)

while direction != B:
  if direction == LEFT:
    if brightness > 3:
      brightness=brightness-1
      rgb.brightness(brightness)
      print(brightness)
      direction = 0
  if direction == RIGHT:
    if brightness < 32:
      brightness=brightness+1
      rgb.brightness(brightness)
      print(brightness)
      direction = 0
  th = time.strftime("%H")
  tm = time.strftime("%M")
  if tm != tmold:
    rgb.clear()
    rgb.text(th, (0, 128, 0), (3, 0))
    rgb.text(tm, (0, 128, 0), (18, 0))
    tmold = tm
  time.sleep(0.2)
system.reboot()