import buttons
import display
import leds
import os
import ujson
import utime
import vibra


CONFIG_NAME = 'tea-timer.json'
DEFAULT_TIMER_SECONDS = 240


def load_config():
    global timer_seconds
    if CONFIG_NAME in os.listdir('.'):
        f = open(CONFIG_NAME, 'r')
        config = ujson.loads(f.read())
        f.close()
        timer_seconds = config.get('timer_seconds', DEFAULT_TIMER_SECONDS)


def save_config():
    config = {'timer_seconds': timer_seconds}
    f = open(CONFIG_NAME, 'w')
    f.write(ujson.dumps(config))
    f.close()


def headline():
    disp.print('Tea Timer', posy=0, fg=[255, 215, 0])


def timeline(seconds):
    mn = seconds // 60
    sc = seconds % 60
    message = '{:02}:{:02}'.format(mn, sc)
    disp.print(message, posy=16, fg=[255, 255, 255])


def timeline_finished():
    message = 'Finished!'
    disp.print(message, posy=16, fg=[255, 255, 255])


def reset():
    global timer_state, pulse_ticks, leds_on
    timer_state = 0
    pulse_ticks = 0
    leds_on = False
    leds.clear()


disp = display.open()
timer_seconds = DEFAULT_TIMER_SECONDS
timer_state = 0  # 0 = setup, 1 = running, 2 = finished
start_time = 0
pulse_ticks = 0
leds_on = False
load_config()

while True:
    pressed = buttons.read(
        buttons.BOTTOM_LEFT | buttons.BOTTOM_RIGHT | buttons.TOP_RIGHT)
    if pressed & buttons.BOTTOM_LEFT != 0:
        if timer_state == 0 and timer_seconds > 30:
            timer_seconds -= 30
            save_config()
        elif timer_state == 2:
            reset()
    if pressed & buttons.BOTTOM_RIGHT != 0:
        if timer_state == 0 and timer_seconds < 600:
            timer_seconds += 30
            save_config()
        elif timer_state == 2:
            reset()
    if pressed & buttons.TOP_RIGHT != 0:
        if timer_state == 0:
            start_time = utime.time()
            timer_state = 1
        elif timer_state == 2:
            reset()

    disp.clear()
    headline()
    if timer_state == 0:
        timeline(timer_seconds)
    if timer_state == 1:
        seconds = timer_seconds - (utime.time() - start_time)
        timeline(seconds)
        if seconds == 0:
            timer_state = 2
    if timer_state == 2:
        timeline_finished()
        if pulse_ticks == 0:
            if leds_on:
                leds.clear()
            else:
                leds.gay(0.4)
                vibra.vibrate(200)
            leds_on = not leds_on
            pulse_ticks = 5
        else:
            pulse_ticks -= 1
    disp.update()

    utime.sleep_ms(100)
