import appglue
import badge
import dialogs
import time
import ugfx
import urequests
import wifi

restart = False

def on_start(pressed):
    if pressed:
        appglue.home()

def on_b(pressed):
    global restart
    if pressed:
        badge.nvs_set_str('db_departures', 'station_id', "")
        restart = True

def load_departures(station_id):
    try:
        response = urequests.get("https://dbf.finalrewind.org/{}?mode=json&version=3&limit=8".format(station_id))
        return response.json()['departures']
    except:
        return None

def update_departure_list(station_id):
    departures = load_departures(station_id)
    if departures is not None:
        draw_departure_list(departures, station_id)

def draw_departure_list(departures, station_id):
    ugfx.clear(ugfx.WHITE)
    ugfx.flush()
    width = ugfx.width()
    ugfx.string_box(0, 0, width, 13, "Departures in {}".format(station_id), "Roboto_Regular12", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.line(0, 13, width, 13, ugfx.BLACK)
    ugfx.string_box(0, 13*9, width, 13, "START: Home   B: Choose station", "Roboto_Regular12", ugfx.BLACK, ugfx.justifyLeft)
    for i, train in enumerate(departures[:8]):
        draw_train(train, 0, 13*i + 13, width, 13)
    ugfx.flush()

def draw_train(train, x, y, width, height):
    ugfx.string_box(x, y, 25, height, train['platform'], "Roboto_Regular12", ugfx.BLACK, ugfx.justifyLeft)
    ugfx.string_box(x+25, y, 60, height, train['train'].replace(" ", ""), "Roboto_Regular12", ugfx.BLACK, ugfx.justifyLeft)
    ugfx.string_box(x+85, y, width-85, height, replace_umlauts(train['destination']), "Roboto_Regular12", ugfx.BLACK, ugfx.justifyLeft)
    if train['scheduledDeparture']:
        ugfx.string_box(x, y, width-30, height, train['scheduledDeparture'], "Roboto_Regular12", ugfx.BLACK, ugfx.justifyRight)
        if train['delayDeparture'] > 0:
            ugfx.string_box(x+width-30, y, 30, height, "+{}".format(train['delayDeparture']), "Roboto_Regular12", ugfx.BLACK, ugfx.justifyRight)
        elif train['delayDeparture'] < 0:
            ugfx.string_box(x+width-30, y, 30, height, "-{}".format(abs(train['delayDeparture'])), "Roboto_Regular12", ugfx.BLACK, ugfx.justifyRight)
    elif train['scheduledArrival']:
        ugfx.string_box(x, y, width-30, height, train['scheduledArrival'], "Roboto_Regular12", ugfx.BLACK, ugfx.justifyRight)
        if train['delayArrival'] > 0:
            ugfx.string_box(x+width-30, y, 30, height, "+{}".format(train['delayArrival']), "Roboto_Regular12", ugfx.BLACK, ugfx.justifyRight)
        elif train['delayArrival'] < 0:
            ugfx.string_box(x+width-30, y, 30, height, "-{}".format(abs(train['delayArrival'])), "Roboto_Regular12", ugfx.BLACK, ugfx.justifyRight)
    ugfx.line(x, y+height, x+width, y+height, ugfx.BLACK)

def replace_umlauts(text):
    return text.replace("ä", "ae").replace("ö", "oe").replace("ü", "ue").replace("ß", "ss")

def run():
    global restart

    wifi.connect()
    if not wifi.wait(30, True):
        exit()

    ugfx.orientation(0)
    ugfx.set_lut(ugfx.LUT_NORMAL)
    ugfx.input_attach(ugfx.BTN_START, on_start)
    ugfx.input_attach(ugfx.BTN_B, on_b)

    station_id = badge.nvs_get_str('db_departures', 'station_id', None)
    if not station_id:
        station_id = dialogs.prompt_text("Station ID? (e.g. FFW)").upper()
        badge.nvs_set_str('db_departures', 'station_id', station_id)
        restart = False

    ugfx.clear(ugfx.WHITE)
    ugfx.string_box(0,10,296,26, "Please be very patient...", "Roboto_Regular12", ugfx.BLACK, ugfx.justifyCenter)
    ugfx.flush()
    ugfx.set_lut(ugfx.LUT_FULL)
    seconds_since_update = 999
    while not restart:
        if seconds_since_update >= 30:
            update_departure_list(station_id)
            seconds_since_update = 0
        time.sleep(1)
        seconds_since_update += 1


while True:
    run()