__doc__='Power mod by Atrant of Lite filemanager by Shrim'
__name__='PowLite FM'
class manager:
  def __s2d(s,x):
    res = ""
    x = x.lower()
    for i in range(len(x)):
      ind = s.alphabet.find(x[i])
      if ind == -1: res += "1"
      else: res += s.numaplhabet[ind]
    return res
  def ru(s,x):
    return x.decode('utf-8')
  def ur(s,x):
    return x.encode('utf-8')
  def __init__(s):
    import appuifw,os,e32
    s.appuifw, s.os, s.e32 = appuifw,os,e32
    s.lock = s.e32.Ao_lock()
    s.curdir = None
    s.alphabet =  s.ru("abcdefghijklmnopqrstuvwxyzабвгдеёжзийклмнопрстуфхцчшщьыъэюя1234567890 ")
    s.numaplhabet =   u"2223334445556667777888999922223333344445555666677778888999912345678900"
  def AskUser(s, path = None, find = 'file', ext = [], soundmod = False):
    s.soundmod = soundmod
    if s.soundmod:
      import audio, keycapture
      s.audio, s.keycapture = audio, keycapture
      s.capturer = s.keycapture.KeyCapturer(s.keycap)
      s.capturer.forwarding = 0
      s.capturer.keys = s.keycapture.all_keys

    s.iconpath = __file__[:-2]+u"mbm"
    if not s.os.path.exists(s.iconpath):
      if s.os.path.exists(u"e"+s.iconpath[1:]):
        s.iconpath = u"e"+s.iconpath[1:]
      else:
        s.appuifw.app.note(s.ru("Thiếu tập tin"),'error')
        return None

    icon = s.appuifw.Icon(s.iconpath,8,9)
    s.workitem = (s.ru('Vui lòng chờ...'),icon)
    icon = s.appuifw.Icon(s.iconpath,6,7)
    s.backitem = (u'<<<',icon)

    if path == None and s.curdir != None and s.curdir != u'root':
      path = s.os.path.split(s.curdir)[0]
      if path[-1] != '\\': path += '\\'
    s.oldscreen = s.appuifw.app.screen
    s.oldbody = s.appuifw.app.body
    s.oldexitkeyhandler = s.appuifw.app.exit_key_handler
    s.oldmenu = s.appuifw.app.menu
    s.oldtitle = s.appuifw.app.title
    try:
      s.oldfocus = s.appuifw.app.body.focus
      s.appuifw.app.body.focus = False
    except: pass
    if find == 'dir': s.appuifw.app.title = s.ru("Chọn thư mục")
    else: s.appuifw.app.title = s.ru("Chọn tập tin")

    s.find, s.ext = find, ext

    s.appuifw.app.screen = 'normal'
    s.appuifw.app.body = s.body = s.appuifw.Listbox(s.list_root())
    s.appuifw.app.exit_key_handler = s.exit
    s.menuChoose = (s.ru("Chọn"),s.choose_item)
    s.menuOpen = (s.ru("Mở"),s.browse_forward)
    s.menuBack = (s.ru("Quay về"),s.browse_back)

    s.curlist = s.list_root()

    if not path: s.root()
    else:
      try:
        path = s.ru(path)
      except:
        pass
      s.curdir = s.os.path.normpath(path)
      if s.os.path.exists(s.ur(s.curdir)):
        pfile = None
        if s.os.path.isfile(s.ur(path)):
          pfile = s.os.path.basename(s.curdir).lower()
          s.curdir = s.os.path.dirname(s.curdir)
        if s.os.path.isdir(s.ur(s.curdir)): 
          if s.curdir[-1] != '\\':
            s.curdir = s.curdir + '\\'
        s.listdir(posfile = pfile)
      else: s.root()

    s.body.bind(63495,s.browse_back)
    s.body.bind(63557,s.browse_forward)
    s.body.bind(63496,s.choose_item)
    s.body.bind(63497,lambda: s.construct_menu(-1))
    s.body.bind(63498,lambda: s.construct_menu(1))
    s.body.bind(48,lambda: s.listslice(u"0"))
    s.body.bind(49,lambda: s.listslice(u"1"))
    s.body.bind(50,lambda: s.listslice(u"2"))
    s.body.bind(51,lambda: s.listslice(u"3"))
    s.body.bind(52,lambda: s.listslice(u"4"))
    s.body.bind(53,lambda: s.listslice(u"5"))
    s.body.bind(54,lambda: s.listslice(u"6"))
    s.body.bind(55,lambda: s.listslice(u"7"))
    s.body.bind(56,lambda: s.listslice(u"8"))
    s.body.bind(57,lambda: s.listslice(u"9"))
    s.body.bind(8,lambda: s.listslice(u"C"))
    s.construct_menu(0)

    s.lock.wait()

    s.body.bind(63495,None)
    s.body.bind(63557,None)
    s.body.bind(63496,None)
    s.body.bind(63497,None)
    s.body.bind(63498,None)
    s.body.bind(48,None)
    s.body.bind(49,None)
    s.body.bind(50,None)
    s.body.bind(51,None)
    s.body.bind(52,None)
    s.body.bind(53,None)
    s.body.bind(54,None)
    s.body.bind(55,None)
    s.body.bind(56,None)
    s.body.bind(57,None)
    s.appuifw.app.body = s.oldbody
    s.appuifw.app.screen = s.oldscreen
    s.appuifw.app.exit_key_handler = s.oldexitkeyhandler
    s.appuifw.app.menu = s.oldmenu
    s.appuifw.app.title = s.oldtitle
    try: s.appuifw.app.body.focus = s.oldfocus
    except: pass
    tmp = None
    if s.choice_made:
      tmp = s.curdir
      if s.find == 'dir' and tmp[:-1]!='\\':
        tmp += '\\'

    if s.curdir != u'root':
      if s.find == 'file':
        s.curdir = s.os.path.split(s.curdir)[0]
      if s.curdir[-1] != '\\': s.curdir += '\\'
    #try:s.appuifw.note(tmp,'info')
    #except: pass
    return tmp

  def root(s, prevdir = None):
    if s.appuifw.app.title[-1] == u"*":
      s.appuifw.app.title = s.appuifw.app.title[:-1]
    t = s.list_root()
    posindex = 0
    for i in range(len(t)):
      #s.appuifw.note(t[i][0])
      if t[i][0] == prevdir:
        posindex = i
        break
    s.body.set_list(t,posindex)
    s.curdir = u'root'
    s.curlist = s.list_root()
    s.construct_menu(0)
  
  def playsound(s):
    global s_fm
    s.capturer.start()
    try:
      i = s.body.current()
      path = s.curdir + s.curlist[i][0]
      s_fm = s.audio.Sound.open(path)
      s_fm.play(times = 1, callback = s.AudioCallback)
    except:
      s.capturer.stop()
    
  def AudioCallback(s,prev_state, cur_state, err_code):
    if prev_state == s.audio.EPlaying: # то есть файл закончил проигрываться
      s.capturer.stop()

  def keycap(s, key):
    global s_fm
    try:
      s_fm.stop()
      s_fm.close()
    except:pass
    s.capturer.stop()
  
  def choose_cur_dir(s):
    s.browse_back()
    s.choose_item()
  
  def construct_menu(s, add):
    def _set(x):
      if s.soundmod and len(x) > 1 and s.menuChoose in x:
        x = [(s.ru("Phát"), s.playsound)] + x
      elif s.find == 'dir' and s.curdir != 'root':
        x = [(s.ru("Đánh dấu đã chọn"), s.choose_cur_dir)] + x 
      s.appuifw.app.menu = x

    i = s.body.current() + add
    if i == -1: i = len(s.curlist) - 1
    elif i == len(s.curlist): i = 0
    if s.curdir == u'root':
      if s.find == 'dir':
        _set([s.menuChoose,s.menuOpen])
      else: _set([s.menuOpen])
      return
    elif i == 0:
      _set([s.menuChoose])
      return
    else:
      path = s.curdir + s.curlist[i][0]

    if s.os.path.isdir(s.ur(path)):
      if s.find == 'dir':
        _set([s.menuChoose,s.menuOpen,s.menuBack])
      else:
        _set([s.menuOpen,s.menuBack])
    else:
      _set([s.menuChoose,s.menuBack])

  def list_root(s):
    icon = s.appuifw.Icon(s.iconpath,0,1)
    resultlist = []
    for drive in s.e32.drive_list():
      resultlist.append((drive,icon))
    return resultlist

  def listslice(s,keycode):
    if s.curdir == u'root': return
    if keycode == u"C":
      if s.curnumstring == u"":
        return
      s.curnumstring = s.curnumstring[:-1]
      if s.curnumstring == u"":
        if s.appuifw.app.title[-1] == u"*":
          s.appuifw.app.title = s.appuifw.app.title[:-1]
        s.curlist = s.fulllist
        s.body.set_list(s.fulllist)
        return
    else: s.curnumstring += keycode
    if s.appuifw.app.title[-1] != u"*":
      s.appuifw.app.title += u"*"
    resultlist = [s.curlist[0]]
    #s.appuifw.note(s.curnumstring)
    for i in range(0,len(s.curnumlist)):
      if s.curnumlist[i].startswith(s.curnumstring):
        resultlist.append(s.fulllist[i+1])
    s.curlist = resultlist
    index = 0
    if len(resultlist) > 1: index = 1
    s.body.set_list(resultlist,index)

  def listdir(s, prevdir = None, posfile = None):
    #if prevdir:
      #s.appuifw.note(prevdir)
    if s.appuifw.app.title[-1] == u"*":
      s.appuifw.app.title = s.appuifw.app.title[:-1]
    resultlist = [s.backitem]
    s.curnumlist = []
    s.curnumstring = u""
    s.body.set_list( [s.workitem])
    s.e32.ao_yield()
    templist, files, folders = s.  os.listdir(s.ur(s.curdir)), [], []
    posindex = 0

    if templist:
      for item in templist:
        if s.os.path.isfile(s.ur(s.curdir) + item):
          if s.find == 'file':
            if len(s.ext)>0:
              for extension in s.ext:
                if s.os.path.splitext(item)[1].lower() == extension.lower():
                  files.append(item)
            else: files.append(item)
        else: folders.append(item)
      templist = folders
      for i in range(len(templist)):
        item = s.ru(templist[i])
        if item.lower() == prevdir:
          posindex = i+1
        icon = s.appuifw.Icon(s.iconpath,2,3)
        resultlist.append((item,icon))
        s.curnumlist.append(s.__s2d(item))
      templist = files
      for i in range(len(templist)):
        item = s.ru(templist[i])
        if item.lower() == posfile:
          posindex = len(folders) + i + 1
        icon = s.appuifw.Icon(s.iconpath,4,5)
        resultlist.append((item,icon))
        s.curnumlist.append(s.__s2d(item))

    s.body.set_list(resultlist,posindex)
    s.curlist = resultlist
    s.fulllist = resultlist
    s.construct_menu(0)

  def browse_back(s):
    if s.curdir == u'root': return
    elif len(s.curdir) == 3:
      #s.appuifw.note(s.curdir[:-1])
      s.root(s.curdir[:-1])
    else:
      ind = s.curdir[:-1].rfind('\\')
      prevdir = s.curdir[ind+1:-1].lower()
      #s.appuifw.note(prevdir)
      s.curdir = s.os.path.dirname(s.curdir[:-1])
      if s.curdir[-1] != '\\': s.curdir += '\\'
      s.listdir(prevdir)

  def browse_forward(s):
    i = s.body.current()
    if s.curdir == u'root':
      path = s.e32.drive_list()[i]  + '\\'
    elif i == 0:
      s.browse_back()
      return
    else:
      path = s.curdir + s.curlist[i][0] + '\\'

    if s.os.path.isdir(s.ur(path)):
      s.curdir = path
      s.listdir()
    else:
      s.choose_item()

  def ch_made(s, p):
    s.curdir = p
    s.choice_made = True
    s.lock.signal()

  def choose_item(s):
    i = s.body.current()
    #s.appuifw.note(s.curnumlist[i-1])
    #return
    if s.curdir == u'root':
      if s.find == 'dir':
        s.ch_made(s.e32.drive_list()[i] + '\\')
    elif i == 0:
      s.browse_back()
    else:
      item = s.curdir + s.curlist[i][0]

      if s.os.path.isdir(s.ur(item)):
        if s.find == 'dir':
          s.ch_made(item)
      else:
        s.ch_made(item)

  def exit(s):
    s.choice_made = False
    s.lock.signal()
