import os
import buttons
import utime
import display
import ujson
import color
import leds

DIR = "apps/fahrplan"
FILENAME = "schedule.json"
MAXCHARS = 11

DE_FLAG = [[(49, 52, 49),(16, 16, 16),(16, 16, 16),(16, 12, 16),(8, 12, 8),(8, 12, 8),(8, 8, 8),(8, 8, 8),(8, 8, 8),(8, 4, 8),(8, 4, 8),(0, 4, 0),(0, 0, 0),(0, 0, 0),(0, 0, 0),(41, 40, 41),],[(65, 64, 65),(24, 20, 24),(16, 20, 16),(16, 20, 16),(16, 16, 16),(16, 16, 16),(16, 16, 16),(16, 12, 16),(16, 12, 16),(8, 12, 8),(8, 12, 8),(8, 8, 8),(8, 8, 8),(8, 8, 8),(8, 4, 8),(49, 52, 49),],[(65, 64, 65),(16, 24, 24),(16, 24, 24),(16, 24, 24),(16, 20, 24),(16, 20, 16),(16, 20, 16),(16, 16, 16),(8, 16, 16),(8, 16, 16),(8, 12, 16),(8, 12, 16),(8, 12, 8),(8, 12, 8),(0, 8, 8),(49, 52, 57),],[(180, 68, 65),(172, 28, 32),(172, 28, 24),(172, 24, 24),(172, 24, 24),(172, 24, 24),(172, 24, 24),(172, 20, 24),(172, 20, 16),(172, 20, 16),(172, 20, 16),(172, 16, 16),(172, 16, 16),(172, 16, 16),(172, 12, 16),(172, 56, 57),],[(213, 72, 74),(222, 32, 32),(222, 32, 32),(222, 32, 32),(222, 28, 32),(222, 28, 24),(222, 28, 24),(222, 24, 24),(222, 24, 24),(222, 24, 24),(222, 20, 24),(222, 20, 24),(222, 20, 16),(222, 20, 16),(222, 16, 16),(213, 60, 57),],[(213, 76, 74),(222, 36, 32),(222, 36, 32),(222, 36, 32),(222, 32, 32),(222, 32, 32),(222, 32, 32),(222, 28, 32),(222, 28, 32),(222, 28, 24),(222, 24, 24),(222, 24, 24),(222, 24, 24),(222, 24, 24),(222, 20, 24),(213, 64, 65),],[(222, 109, 74),(230, 85, 41),(230, 85, 41),(230, 80, 41),(230, 80, 41),(230, 80, 32),(230, 80, 32),(230, 80, 32),(230, 76, 32),(230, 76, 32),(230, 76, 32),(230, 76, 32),(230, 72, 24),(230, 72, 24),(230, 72, 24),(222, 101, 65),],[(230, 202, 57),(255, 210, 24),(255, 218, 41),(255, 218, 41),(255, 218, 41),(255, 218, 41),(255, 218, 41),(255, 218, 41),(255, 218, 32),(255, 218, 32),(255, 214, 32),(255, 214, 32),(255, 214, 32),(255, 214, 32),(255, 214, 32),(238, 206, 65),],[(230, 194, 49),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 202, 8),(246, 202, 16),(246, 206, 24),(255, 206, 24),(255, 206, 32),(255, 210, 32),(255, 210, 32),(255, 210, 32),(255, 210, 32),(255, 210, 24),(255, 206, 24),(238, 202, 65),],[(230, 194, 41),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 198, 0),(246, 198, 0),(230, 194, 41),]]

UK_FLAG = [[(213, 105, 115),(246, 202, 205),(205, 218, 238),(32, 64, 139),(8, 44, 131),(8, 44, 131),(82, 109, 172),(222, 76, 90),(222, 72, 90),(74, 109, 172),(8, 40, 131),(0, 36, 123),(24, 64, 148),(180, 117, 148),(222, 85, 98),(238, 222, 222),],[(106, 129, 172),(205, 121, 139),(222, 105, 123),(255, 255, 255),(123, 141, 189),(8, 40, 131),(82, 113, 172),(222, 76, 90),(222, 76, 90),(82, 113, 172),(0, 36, 123),(115, 125, 172),(222, 85, 98),(238, 170, 180),(230, 242, 246),(90, 113, 164),],[(65, 85, 148),(8, 48, 131),(139, 133, 172),(222, 85, 98),(246, 190, 197),(222, 226, 238),(115, 141, 189),(222, 80, 98),(222, 80, 98),(115, 141, 189),(197, 125, 148),(222, 89, 106),(255, 250, 255),(131, 149, 189),(0, 32, 123),(49, 76, 139),],[(197, 206, 222),(197, 210, 230),(197, 206, 230),(230, 242, 255),(246, 198, 205),(255, 250, 255),(255, 255, 255),(222, 80, 98),(222, 80, 98),(255, 250, 246),(246, 210, 213),(255, 255, 255),(222, 234, 246),(189, 206, 230),(197, 206, 230),(189, 202, 222),],[(205, 76, 90),(213, 36, 57),(213, 36, 57),(205, 36, 57),(205, 32, 57),(205, 32, 57),(205, 32, 49),(213, 40, 65),(213, 40, 57),(205, 28, 49),(205, 28, 49),(205, 24, 49),(205, 24, 49),(205, 24, 49),(205, 20, 41),(205, 64, 82),],[(205, 80, 90),(213, 40, 65),(213, 40, 65),(213, 40, 57),(213, 40, 57),(213, 36, 57),(205, 36, 57),(213, 44, 65),(213, 44, 65),(205, 32, 57),(205, 32, 49),(205, 28, 49),(205, 28, 49),(205, 28, 49),(205, 28, 49),(205, 68, 82),],[(197, 206, 222),(205, 214, 230),(197, 210, 230),(230, 234, 246),(255, 255, 255),(246, 214, 222),(255, 250, 246),(222, 89, 106),(222, 89, 106),(255, 255, 255),(255, 250, 255),(246, 202, 205),(230, 242, 255),(197, 210, 230),(197, 210, 230),(197, 206, 222),],[(57, 80, 139),(16, 48, 131),(148, 165, 197),(255, 255, 255),(230, 109, 123),(205, 137, 156),(131, 153, 197),(222, 93, 106),(222, 93, 106),(123, 149, 197),(222, 230, 238),(246, 194, 197),(222, 89, 106),(139, 137, 180),(16, 48, 131),(65, 89, 148),],[(90, 109, 156),(222, 230, 238),(230, 161, 172),(213, 76, 90),(115, 121, 164),(8, 40, 123),(90, 113, 172),(222, 85, 98),(222, 89, 106),(90, 121, 180),(24, 52, 131),(131, 145, 189),(255, 255, 255),(222, 113, 123),(205, 121, 139),(106, 133, 172),],[(230, 214, 213),(213, 80, 98),(172, 113, 139),(24, 60, 139),(0, 32, 115),(0, 32, 123),(65, 101, 164),(213, 64, 82),(213, 64, 82),(65, 97, 164),(0, 32, 115),(0, 28, 115),(16, 52, 131),(197, 206, 222),(238, 190, 197),(205, 93, 106),],]

def render_error(err1, err2):
    with display.open() as disp:
        disp.clear()
        disp.print(err1, posx=80 - round(len(err1) / 2 * 14), posy=18)
        disp.print(err2, posx=80 - round(len(err2) / 2 * 14), posy=42)
        disp.update()
        disp.close()


def draw_flag(flag):
    flag_x, flag_y = 140, 44
    for x, list_y in enumerate(flag):
        for y, color in enumerate(list_y):
           disp.pixel(flag_x + y, flag_y + x, col=color)

def draw_event(event, disp, offset, daysCount):
    disp.clear()
    disp.rect(0, 0, 159, 20, col=color.CHAOSBLUE) 
    disp.rect(0, 20, 159, 80, col=color.CHAOSBLUE)

    for i in range(daysCount):
        if i == int(event["day"]) - 1:
            leds.set(10-i, [0, 255, 0])
        else:
            leds.set(10-i, [255, 0, 0])

    title = event['title'] + " -- "
    linelen = len(title)
    offset %= linelen
    post_title = ""
    if offset + MAXCHARS > linelen:
        post_title = title[:(offset + MAXCHARS - linelen)]
    disp.print(title[offset: offset + MAXCHARS] + post_title, posy=0, fg=color.CAMPGREEN, bg=color.CHAOSBLUE)

    disp.print("D " + event["day"] + " - " + event['start'], posy=20, bg=color.CHAOSBLUE)
    disp.print(event['room'], posy=40, bg=color.CHAOSBLUE)

    e_duration = event["duration"]
    duration = ""
    if e_duration[0] != '0':
        duration += e_duration[0:2] + "h"
    elif e_duration[1] != '0':
        duration += e_duration[1] + "h"

    if e_duration[3] != '0':
        duration += e_duration[3:5] + "m"
    elif e_duration[4] != '0':
        duration += e_duration[4] + "m"

    if event['language'] == 'en':
        draw_flag(UK_FLAG)
    elif event['language'] == 'de':
        draw_flag(DE_FLAG)


    disp.print(duration + " long", posy=60, bg=color.CHAOSBLUE)
    disp.update()


def process_json(f):
    try:
        conf = ujson.loads(f.read())
        events = conf["events"]
        daysCount = conf["daysCount"]
    except Exception as e:
        return None

    events = sorted(events, key=lambda e: e['timestamp'])
    return events, daysCount


def compute_next_event_nb(event_list):
    t = utime.time()
    i = 0
    max_len = len(event_list)
    while i < max_len and event_list[i]["timestamp"] < t:
        i += 1
    if i == max_len:
        i -= 1
    return i


print("Start")
if FILENAME not in os.listdir(DIR):
    render_error('file not', 'found')
    print("File not found")
else:
    leds.dim_top(1)
    events = None
    with open(DIR + "/" + FILENAME) as f:
        events, daysCount = process_json(f)
    if not events:
        render_error('error prossessing', 'events')
        print("Error processing events")
    else:
        event_nb = compute_next_event_nb(events)
        len_events = len(events)

        i = -7
        offset = 0
        disp = display.open()

        while 1:
            draw_event(events[event_nb], disp, offset, daysCount)
            i += 1
            if i >= 4:
                offset += 1
                i = 0

            # Process button event
            v = buttons.read(buttons.BOTTOM_LEFT | buttons.BOTTOM_RIGHT | buttons.TOP_RIGHT)
            if v == 0:
                button_pressed = False

            if not button_pressed and v & buttons.BOTTOM_LEFT != 0:
                button_pressed = True
                event_nb -= 1
                if event_nb < 0:
                    event_nb = 0
                offset = 0
                i = -7

            if not button_pressed and v & buttons.BOTTOM_RIGHT != 0:
                button_pressed = True
                event_nb += 1
                if event_nb >= len_events:
                    event_nb = len_events - 1
                offset = 0
                i = -7

            if not button_pressed and v & buttons.TOP_RIGHT != 0:
                button_pressed = True
                event_nb = compute_next_event_nb(events)
                offset = 0
                i = -7

            utime.sleep_ms(10)
