# emacs-mode: -*- python-*-
import mwif
import os
import os.path
import e32
import audio
import graphics
from wif_keys import *
items = {}
path = []
pos = mwif.app.cur_pos
adr = ''
result = None

def show(l):
    global items
    global adr
    men.clear()
    men.title = adr
    it = 0
    items = {}
    adr = ''
    for i in range(len(path)):
        adr = ((adr + path[i]) + '\\')

    for i in range(len(l)):
        if os.path.isdir((adr + l[i])):
            men.row_link(mwif.dec((l[i] + '\\')), select, color=16711680, font='legend')
            items[it] = l[i]
            it = (it + 1)

    for i in range(len(l)):
        fadr = (adr + l[i])
        if ((os.path.isfile(fadr) and (filemask == '*')) or (os.path.isfile(fadr) and fadr.endswith(filemask))):
            men.row_link(l[i], select, color=240, font='dense')
            items[it] = l[i]
            it = (it + 1)




def select():
    global adr
    global pos
    global result
    pos = mwif.app.cur_pos
    if (pos == None):
        return 
    res = None
    try:
        res = items[pos]
    except:
        return 
    adr = ''
    for i in range(len(path)):
        adr = ((adr + path[i]) + '\\')

    if os.path.isfile((adr + res)):
        mwif.signal()
        result = (adr + res)
        return 
    path.append(res)
    adr = ''
    for i in range(len(path)):
        adr = ((adr + path[i]) + '\\')

    d = os.listdir(adr)
    show(d)



def back():
    global path
    if (len(path) > 1):
        path.pop()
        adr = ''
        for i in range(len(path)):
            adr = ((adr + path[i]) + '\\')

        d = os.listdir(adr)
    else:
        path = []
        d = drive
    show(d)



def manager(fm = '*'):
    global path
    global filemask
    global men
    global drive
    filemask = fm
    men = mwif.Screen()
    men.color = (16777136,
     16711680)
    men.cur_color = (16711680,
     15790080)
    men.bind(KLEFT, back)
    men.bind(KRIGHT, select)
    mwif.show(men)
    path = []
    adr = ''
    t = e32.drive_list()
    drive = []
    for i in range(len(t)):
        drive.append(mwif.enc(t[i]))

    show(drive)
    mwif.wait()
    mwif.run = 1
    mwif.hide()
    return result.decode('utf-8')



# local variables:
# tab-width: 4
