import wx
import os
import Image
import  wx.lib.mixins.listctrl as lc
exts = ['.jpg', '.png']

def fileToThumb(file, tsize):
        pil = Image.open(file)
        pil.thumbnail(tsize, Image.ANTIALIAS)
        image = wx.EmptyImage(pil.size[0], pil.size[1])
        image.SetData(pil.convert('RGB').tostring())
        return image.ConvertToBitmap()

class ThumbnailBrowser(wx.ListCtrl, lc.ListCtrlSelectionManagerMix):
    def __init__(self, parent, path, tsize = (200,200)):
        wx.ListCtrl.__init__(self, parent, -1,style=wx.LC_VIRTUAL|wx.LC_VRULES)
        self.path = path
        self.tsize = tsize
        wx.EVT_LIST_BEGIN_DRAG(self, self.GetId(), self.OnDrag)
        wx.EVT_CHAR(self, self.OnChar)
        wx.EVT_MOUSEWHEEL(self, self.OnMouseWeel)
        self.Refresh()
    
    def Refresh(self):
        self.tlist = []
        if not os.path.isdir(self.path):
            self.path = os.getcwd()
        self.il = wx.ImageList(self.tsize[0], self.tsize[1], initialCount=0)
        for thumb in os.listdir(self.path):
            name, ext = os.path.splitext(thumb)
            if ext.lower() in exts:
                fullpath = os.path.join(self.path, thumb)
                self.tlist.append(fullpath)
                self.il.Add(wx.EmptyImage(self.tsize[0], self.tsize[1]).ConvertToBitmap()) 
                self.il.Replace(self.il.GetImageCount()-1, fileToThumb(fullpath, self.tsize)) 
                
        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 OnMouseWeel(self, evt):
        if evt.ControlDown():
            print "zooming"
        else:
            evt.Skip()
    
    def OnChar(self, evt):
        if evt.m_keyCode == 115:
            print "rotate left"
        elif evt.m_keyCode == 100:
            print "rotate right"
        sel = self.getSelection()
        
        self.Refresh()
        self.SetSelection(sel)
        evt.Skip()
    
    def OnDrag(self, evt):
        print "look ma, I'm being dragged"
        selection =  self.getSelection()
        dropSource = wx.DropSource(self)
        data = wx.FileDataObject()

        for index in selection:
            data.AddFile(self.tlist[index])
        dropSource.SetData(data)
        result = dropSource.DoDragDrop(wx.Drag_AllowMove)
        print result
        
        
    def OnGetItemImage(self, item):
        return item

    def OnGetItemText(self, item, col):
        dir, filename = os.path.split(self.tlist[item])
        return filename

    def OnGetItemAttr(self, item):
        return None


#------------------------------- Testing Code --------------------------------
try:
    app = wx.PySimpleApp()
    frame =  wx.Frame(None, -1, "Test")
    app.SetTopWindow(frame)
    tb = ThumbnailBrowser(frame, os.getcwd())
    frame.Show()
    app.MainLoop()
except:
    import traceback
    traceback.print_exc()
    dlg = wx.MessageDialog(None, "","Error!", wx.OK)
    dlg.ShowModal()
    dlg.Destroy()