import wx
import os
import Image
import  wx.lib.mixins.listctrl as lc

class FBDropTarget(wx.FileDropTarget):
    def __init__(self, target):
        wx.FileDropTarget.__init__(self)
        self.target = target
    
    def OnDropFiles(self, x, y, filelist):
        print "\nDrop Data:\ntarget: ", self.target
        print "dropped files: "
        for file in filelist:
            print "\t", file

class FileBrowser(wx.ListCtrl, lc.ListCtrlSelectionManagerMix):
    def __init__(self, parent, path, tsize = 4):
        wx.ListCtrl.__init__(self, parent, -1,style=wx.LC_VIRTUAL|wx.LC_VRULES|wx.LC_LIST)
        
        self.path = path
        wx.EVT_LIST_BEGIN_DRAG(self, self.GetId(), self.OnDrag)
        self.SetDropTarget(FBDropTarget(self.path))
        self.Load()
        
    def Load(self):
        self.tlist = []
        if not os.path.isdir(self.path):
            print "invalid path: ", self.path
            self.path = os.getcwd()        
        self.il = wx.ImageList(16, 16, initialCount=0)
        for thumb in os.listdir(self.path):
            name, ext = os.path.splitext(thumb)
            fullpath = os.path.join(self.path, thumb)
            self.tlist.append(fullpath)
        self.AssignImageList(self.il, wx.IMAGE_LIST_NORMAL)
        self.SetItemCount(len(self.tlist))
            
    def setSelection(self, selection):
        idx = -1
        while 1:
            idx = self.GetNextItem(idx)
            if idx in selection:
                self.SetItemState(idx, wx.LIST_STATE_SELECTED, wx.LIST_MASK_STATE)
            if idx == -1:
                break
    
    def OnDrag(self, evt):
        selection =  self._getSelected()
        dropSource = wx.DropSource(self)
        data = wx.FileDataObject()
        print "\nBuilding file list:"
        for file in selection:
            print "\tadding file: ",file
            data.AddFile(file)
        dropSource.SetData(data)
        dropSource.DoDragDrop(wx.Drag_AllowMove)
        
        
    def OnGetItemImage(self, item):
        return 0
        

    def OnGetItemText(self, item, col):
        return os.path.split(self.tlist[item])[1] #return only the filename from (dir, filename) tuple

    def OnGetItemAttr(self, item):
        return None
    
    def _getSelected(self):
        ret = []
        for i in self.getSelection():
            ret.append(self.tlist[i])
        return ret

#------------------------------- Testing Code --------------------------------
if __name__ == '__main__':
    try:
        app = wx.PySimpleApp()
        frame =  wx.Frame(None, -1, "Test")
        app.SetTopWindow(frame)
        fb = FileBrowser(frame, os.getcwd())
        frame.Show()
        app.MainLoop()
    except:
        import traceback
        traceback.print_exc()
        dlg = wx.MessageDialog(None, "","Error!", wx.OK)
        dlg.ShowModal()
        dlg.Destroy()

 