import os
import display
import machine
import system
import ugfx


ROOT_APPDIR = '/lib'

# Clear screen
display.drawFill(0xFFFFFF)
display.flush()


options = ugfx.List(0, 0, ugfx.width(), ugfx.height())
apps = []
# TODO: figure out a generic way to get all apps
for appdir in os.listdir(ROOT_APPDIR):
    # Prolly an app
    if not any(f == 'metadata.json' for f in os.listdir('{}/{}'.format(ROOT_APPDIR, appdir))):
        continue

    options.add_item(appdir)

options.add_item('reset')


def connectClick(pushed):
    if not pushed:
        return

    selected = options.selected_text()
    if selected == 'reset':
        machine.erase_key('system', 'default_app')
    else:
        machine.nvs_setstr('system', 'default_app', selected)
    system.launcher()

ugfx.input_attach(ugfx.BTN_A, connectClick)
ugfx.input_attach(ugfx.BTN_B, lambda pushed: system.launcher() if pushed else 0)
ugfx.input_attach(ugfx.BTN_START, lambda pushed: system.launcher() if pushed else 0)
ugfx.input_attach(ugfx.JOY_UP, lambda pushed: ugfx.flush() if pushed else 0)
ugfx.input_attach(ugfx.JOY_DOWN, lambda pushed: ugfx.flush() if pushed else 0)
ugfx.set_lut(ugfx.LUT_FASTER)
ugfx.flush()