#!/usr/bin/env python
import wx
import sys
import fileinput
from collections import OrderedDict

def todict(X):
    d = OrderedDict()
    for path in X:
        current_level = d
        for part in path:
            if part not in current_level:
                current_level[part] = OrderedDict()
            current_level = current_level[part]
    return d

class TreeFrame(wx.Frame):
  def __init__(self, parent, id, title):
    wx.Frame.__init__(self, parent, id, title, size=(400,600))

    self.tree_ctrl = wx.TreeCtrl(self, -1, style=wx.TR_DEFAULT_STYLE | wx.TR_HIDE_ROOT)

    root = self.tree_ctrl.AddRoot('')

    def append(base, lst):
      for k, v in lst.iteritems():
      #for k, v in sorted(lst.iteritems(), key=lambda (k,v): (v,k)):
        sub = self.tree_ctrl.AppendItem(base, k)
        append(sub, v)

    append(root, structure)

    # if "--expand":
    #   tree_ctrl.ExpandAll()
    self.Centre()
    self.tree_ctrl.Bind(wx.EVT_KEY_UP, self.OnKeyUp)

    # Create the menubar
    menuBar = wx.MenuBar()

    # and a menu
    menu = wx.Menu()

    # add an item to the menu, using \tKeyName automatically
    # creates an accelerator, the third param is some help text
    # that will show up in the statusbar
    menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample")

    # bind the menu event to an event handler
    self.Bind(wx.EVT_MENU, self.Close, id=wx.ID_EXIT)

    # and put the menu on the menubar
    menuBar.Append(menu, "&File")
    self.SetMenuBar(menuBar)
    
  def OnKeyUp(self, event):
    keyCode = event.GetKeyCode()
    if keyCode == wx.WXK_ESCAPE:
      self.Close()
    if keyCode == wx.WXK_RETURN:
        def build_path(item):
            parent = self.tree_ctrl.GetItemParent(item)
            label = self.tree_ctrl.GetItemText(item)
            if parent and parent != self.tree_ctrl.GetRootItem():
                return build_path(parent) + '/' + label
            else:
                return label

        item = self.tree_ctrl.GetSelection()
        label = build_path(item)

        print label
        self.Close()
    if keyCode == wx.WXK_SPACE:
        self.tree_ctrl.ExpandAll()

class ShowAsTree(wx.App):
  def OnInit(self):
    self.frame = TreeFrame(None, -1, '-')
    self.frame.Show(True)
    self.SetTopWindow(self.frame)
    return True

  def SetName(self, name):
    self.frame.SetTitle(name)

if __name__ == '__main__':
  lines = fileinput.input()

  dirs = []
  for l in lines:
    dirs.append(filter(lambda x: len(x) > 0, l.replace('\n', '')[0:].split('/')))
  structure = todict(dirs)

  app = ShowAsTree(0)
  app.SetName(fileinput.filename())
  app.MainLoop()
