import gui
import os

page = 1
directories = []

def vsync_cb(info):
    gui.redraw()

def swipe_cb(gui_list,start):
    global page

    if start:
        pass
    else:
        si = gui.swipe_info()
        if si.dx <= -50:
            if page < (len(directories)/10):
                page += 1
        elif si.dx >= 50:
            if page > 1:
                page -= 1
        draw_default()

def find_directories():
    global directories
    all_dir = os.listdir()
    for item in all_dir:
        try:
            os.chdir('/sd/{}'.format(item))

            contents = os.listdir()
            for file in contents:
                if (file == 'main.py') or (file == 'Main.py'):
                    directories.append(item)

        except OSError: # not a folder
            pass
    directories.sort(key=str.lower)
    os.chdir('/sd')

def run(info):
    global directories
    app = directories[int(info[8])]
    os.chdir('/sd/{}'.format(app))
    try:
        with open('main.py',"r") as r:
            exec(r.read())
    except Exception as e:
        print(e)



def selection():
    global page, directories
    gui_input_list = [
        gui.SUBLIST,
        [gui.DL_COLOR_RGB(0, 0, 0)],
    ]
    drawPage = page
    apps = directories

    if len(directories) > 10:
        apps = directories[10*(drawPage-1):10*(drawPage-1)+10]
    else:
        page = 1

    t_pages = ((len(directories)-1)//10 + 1)
    if t_pages < page:
        t_pages = page

    page_no = "{} OF {}".format(page,t_pages)

    gui_input_list.append([gui.DL_COLOR_RGB(255, 255, 255)])
    gui_input_list.append([gui.CTRL_TEXT, 670, 10, 31, 0, str(page_no)])

    for i, app_name in enumerate(apps):
        gui_input_list.append([gui.DL_COLOR_RGB(0, 0, 0)])
        gui_input_list.append([gui.CTRL_TEXT, 20+390* (i // 5), 80 + (i%5) *70, 29,0,str(app_name)])
        gui_input_list.append([gui.DL_COLOR_RGB(255, 255, 255)])
        gui_input_list.append([gui.CTRL_FLATBUTTON, 200+390* (i // 5), 75 + (i%5) *70, 150, 50, 30, 'RUN', run, str(10*(page-1)+i)])

    if (len(apps) < 1):
        gui_input_list.append([gui.DL_COLOR_RGB(0, 0, 0)])
        gui_input_list.append([gui.CTRL_TEXT, 190, 210, 31, 0, 'NO VALID FILES FOUND'])

    return gui_input_list

def draw_default():
    swipe_r = 50

    gui_l = [
    [gui.EVT_VSYNC, vsync_cb],
    [gui.EVT_SWIPE, swipe_r, swipe_cb],
    [gui.DL_SAVE_CONTEXT()],
    [gui.DL_CLEAR_COLOR_RGB(0, 41, 66)],
    [gui.DL_CLEAR(1, 1, 1)],
    [gui.DL_SCISSOR_SIZE(800, 350)],
    [gui.DL_SCISSOR_XY(0, 65)],
    [gui.DL_CLEAR_COLOR_RGB(255, 255, 255)],
    [gui.DL_CLEAR(1, 1, 1)],
    [gui.DL_RESTORE_CONTEXT()],
    [gui.DL_COLOR_RGB(255, 255, 255)],
    [gui.CTRL_TEXT, 20, 10, 31, 0, 'SELECT APPLICATION TO RUN'],
    ]

    gui_l.append(selection())

    gui.show(gui_l)

def initialise():
    os.chdir('/sd')
    find_directories()
    draw_default()

if __name__ == "__main__":
    initialise()




