import badge, easywifi, ugfx, gc, easydraw, easyrtc, dialogs, deepsleep, time
import urequests as requests

global appname
appname = "OV Vertrektijden"

lastInteraction = time.time()

easydraw.msg("Welkom!", appname)

easywifi.enable(True)
if easywifi.state==False:
    easydraw.msg("Unable to connect to network!","FAILURE")
    easydraw.msg("Waiting 5 seconds to try again!")
    badge.eink_busy_wait()
    import machine
    machine.deepsleep(5000)

easydraw.msg("Updates ophalen...")
try:
    import woezel
    woezel.install('ov_departures')
    easydraw.msg("Geüpdatet, herstarten...")
    badge.eink_busy_wait()
    deepsleep.reboot()
except:
    easydraw.msg("Geen updates beschikbaar.")
    
easyrtc.configure()

def select_busstop(active):
    if active:
        global options
        global locations

        index = options.selected_index()
        options.destroy()
        badge.nvs_set_str("ov_departures", "busstopid", locations[index]['id'])
        easydraw.msg("Bushalte opgeslagen!", appname, True);        

def set_busstop(query):
    if query:
        global options
        global locations

        ugfx.input_attach(ugfx.BTN_A, 0)
        ugfx.clear(ugfx.WHITE)
        ugfx.flush(ugfx.LUT_FULL)

        data = requests.get("http://api.9292.nl/0.1/locations?lang=nl-NL&type=stop&q=" + query.replace(' ', '%20'))
        content = data.json()
        data.close()
        gc.collect()

        ugfx.input_init()
        ugfx.set_default_font("Roboto_Regular12");

        locations = content['locations']
        options = ugfx.List(0,15,ugfx.width(),ugfx.height()-15)

        ugfx.string(0, 0, "Kies bushalte:", "Roboto_Regular12", ugfx.BLACK)

        for location in locations:
            options.add_item("[Halte] %s: %s" % (location['place']['name'], location['name']))

        ugfx.input_attach(ugfx.JOY_UP, lambda pushed: ugfx.flush() if pushed else False)
        ugfx.input_attach(ugfx.JOY_DOWN, lambda pushed: ugfx.flush() if pushed else False)
        ugfx.input_attach(ugfx.BTN_A, select_busstop)	

        ugfx.flush()

        while badge.nvs_get_str("ov_departures", "busstopid", "") == "":
            pass
        gc.collect()

    else:
        easydraw.msg("No query entered!");
        deepsleep.start_sleeping(2000);

def select_station(active):
    if active:
        global options
        global locations
        index = options.selected_index()
        options.destroy()
        badge.nvs_set_str("ov_departures", "stationid", locations[index]['id'])
        easydraw.msg("Treinstation opgeslagen!", appname, True);

def set_station(query):
    if query:
        global options
        global locations

        ugfx.input_attach(ugfx.BTN_A, 0)
        ugfx.clear(ugfx.WHITE)
        ugfx.flush(ugfx.LUT_FULL)

        data = requests.get("http://api.9292.nl/0.1/locations?lang=nl-NL&type=station&q=" + query.replace(' ', '%20'))
        content = data.json()
        data.close()
        gc.collect()

        ugfx.input_init()
        ugfx.set_default_font("Roboto_Regular12");

        locations = content['locations']
        options = ugfx.List(0,15,ugfx.width(),ugfx.height()-15)

        ugfx.string(0, 0, "Kies treinstation:", "Roboto_Regular12", ugfx.BLACK)

        for location in locations:
            options.add_item("[Station] %s (%s)" % (location['name'], location['stationId']))

        ugfx.input_attach(ugfx.JOY_UP, lambda pushed: ugfx.flush() if pushed else False)
        ugfx.input_attach(ugfx.JOY_DOWN, lambda pushed: ugfx.flush() if pushed else False)
        ugfx.input_attach(ugfx.BTN_A, select_station)	

        ugfx.flush()

        while badge.nvs_get_str("ov_departures", "stationid", "") == "":
            pass
        gc.collect()

    else:
        easydraw.msg("No query entered!");
        deepsleep.start_sleeping(2000); 

if badge.nvs_get_str("ov_departures", "busstopid", "") == "":
    easydraw.msg("No bus stop set!", appname, True);
    query = dialogs.prompt_text("Kies een bushalte", "Eindhoven")
    print(query)
    set_busstop(query)
    
if badge.nvs_get_str("ov_departures", "stationid", "") == "":
    easydraw.msg("No nearby train station set!", appname, True);
    query = dialogs.prompt_text("Kies een station", "Eindhoven")
    print(query)
    set_station(query)

easydraw.msg("Gegevens ophalen...", appname)
time.sleep(1)

ugfx.set_default_font("Roboto_Regular12");
ugfx.clear(ugfx.WHITE)
ugfx.flush(ugfx.LUT_FULL)

ugfx.string_box(0, ugfx.height()-14, ugfx.width(), 14, "Laatste update: %s" % (easyrtc.string(True)), "Roboto_Regular12", ugfx.BLACK, ugfx.justifyLeft)

# Bus stop
data = requests.get("http://api.9292.nl/0.1/locations/" + badge.nvs_get_str("ov_departures", "busstopid", "") + "/departure-times?lang=nl-NL")
busstopData = data.json()
data.close()
gc.collect()

for tab in busstopData['tabs']:
    if tab['id'] == "bus":
        busDepartures = tab

ugfx.string_box(0, 0, int(ugfx.width()/2), 15, busDepartures['locations'][0]['name'], "Roboto_Regular12", ugfx.BLACK, ugfx.justifyCenter)

busList = ugfx.List(0,15,int(ugfx.width()/2),ugfx.height()-30)
for departure in busDepartures['departures']:
            busList.add_item("%s - %s %s" % (departure['time'], departure['service'], departure['destinationName']))

del data
del busstopData
del busDepartures 
gc.collect()

# Train station
data = requests.get("http://api.9292.nl/0.1/locations/" + badge.nvs_get_str("ov_departures", "stationid", "") + "/departure-times?lang=nl-NL")
trainstationData = data.json()
data.close()
gc.collect()

for tab in trainstationData['tabs']:
    if tab['id'] == "trein":
        trainDepartures = tab

ugfx.string_box(int(ugfx.width()/2), 0, int(ugfx.width()/2), 15, trainDepartures['locations'][0]['name'], "Roboto_Regular12", ugfx.BLACK, ugfx.justifyCenter)

trainList = ugfx.List(int(ugfx.width()/2),15,int(ugfx.width()/2),ugfx.height()-30)
for departure in trainDepartures['departures']:
            trainList.add_item("%s - %s" % (departure['time'], departure['destinationName']))

del data
del trainstationData
del trainDepartures 
gc.collect()

def refresh_display(active):
    global lastInteraction
    if active:
        lastInteraction = time.time()
        ugfx.flush()

ugfx.input_init()
ugfx.input_attach(ugfx.JOY_UP, refresh_display)
ugfx.input_attach(ugfx.JOY_DOWN, refresh_display)

ugfx.flush()
lastInteraction = time.time()

# Allow for 10 seconds of interaction before going into deep-sleep
while (time.time() - lastInteraction) < 10:
    pass

badge.eink_busy_wait()
# Deep-sleep for 15 minutes
deepsleep.start_sleeping(900000)