import ugfx, badge, network, gc, time, urequests, appglue, sys

# SHA2017 Badge installer
# V2 Thomas Roos
# V1 Niek Blankers

def draw_msg(msg):
    global line_number
    try:
        line_number
    except:
        line_number = 0
        ugfx.clear(ugfx.WHITE)
        ugfx.string(0, 0, 'Still Loading Anyway...', "PermanentMarker22", ugfx.BLACK)
        ugfx.set_lut(ugfx.LUT_FASTER)
        draw_msg(msg)
    else:
        ugfx.string(0, 30 + (line_number * 15), msg, "Roboto_Regular12", ugfx.BLACK)
        ugfx.flush()
        line_number += 1

def connectWiFi():
    nw = network.WLAN(network.STA_IF)
    if not nw.isconnected():
        nw.active(True)
        ssid = badge.nvs_get_str('badge', 'wifi.ssid', 'SHA2017-insecure')
        password = badge.nvs_get_str('badge', 'wifi.password')
        nw.connect(ssid, password) if password else nw.connect(ssid)

        draw_msg("Connecting to '"+ssid+"'...")

        timeout = 150
        while not nw.isconnected():
            time.sleep(0.1)
            timeout = timeout - 1
            if (timeout<1):
                draw_msg("Timeout while connecting!")
                nw.active(True)
                return False
    return True

def show_description(active):
	if active:
		global text
		text.text(packages[options.selected_index()]["description"])
		ugfx.flush()

def select_category(active):
	if active:
		global categories
		global options
		index = options.selected_index()
		if categories[index]["eggs"] > 0:
			category = categories[index]["slug"]
			list_apps(category)