#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.1 on Wed Apr  2 22:17:30 2008

import wx,os,re
import BIB
from moveFile import MoveFile

# begin wxGlade: extracode
# end wxGlade

identifier = ""

class Browser(wx.Panel):
    def __init__(self, *args, **kwds):
        # begin wxGlade: Browser.__init__
        kwds["style"] = wx.TAB_TRAVERSAL
        wx.Panel.__init__(self, *args, **kwds)
        self.label_2 = wx.StaticText(self, -1, _("File/URL ..."))
        self.text_ctrl_filename = wx.TextCtrl(self, -1, "")
        self.button_browse = wx.Button(self, -1, _("Browse"))

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.onBrowse, self.button_browse)
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: Browser.__set_properties
        pass
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: Browser.__do_layout
        sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_4.Add(self.label_2, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_4.Add(self.text_ctrl_filename, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_4.Add(self.button_browse, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
        self.SetSizer(sizer_4)
        sizer_4.Fit(self)
        # end wxGlade

    def onBrowse(self, event): # wxGlade: Browser.<event_handler>
        filename = wx.FileSelector(_("Please select the file"),BIB.FILES,wildcard=BIB.WILDCARD, parent=self )
        if filename:
            if BIB.FILES:
                if not filename.startswith(BIB.FILES) and not filename.startswith("$FILES"):
                    # We propose to move/rename the doc to the default location
                    dlg = MoveFile(self,-1)
                    try:
                        dlg.setValues(identifier,filename,BIB.MOVEAUTO)
                        if not BIB.MOVEAUTO: answer = dlg.ShowModal()
                        if BIB.MOVEAUTO or answer == wx.ID_YES:
                            filename = dlg.rename()
                            #self.value['URL'].SetValue( filename )
                    finally:
                        dlg.Destroy()         
                if filename.startswith(BIB.FILES):    # We replace the default directory with $FILES
                    filename = filename.replace(BIB.FILES,'$FILES',1)
            self.text_ctrl_filename.SetValue( filename )
    
    def GetValue(self):
        return self.text_ctrl_filename.GetValue()
        
    def SetValue(self,filename):
            self.text_ctrl_filename.SetValue( filename )

# end of class Browser


class Panel_Files(wx.Panel):
    def __init__(self, *args, **kwds):
        self.filename = [None,None,None]
        # begin wxGlade: Panel_Files.__init__
        kwds["style"] = wx.TAB_TRAVERSAL
        wx.Panel.__init__(self, *args, **kwds)
        self.panel_scrolled = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL)
        self.button_Auto = wx.Button(self, -1, _("Automatic file detection"))
        self.label_1 = wx.StaticText(self, -1, _("Using pattern"))
        self.choice_pattern = wx.Choice(self, -1, choices=[])
        self.filename[0] = Browser(self.panel_scrolled, -1, )
        self.filename[1] = Browser(self.panel_scrolled, -1)
        self.filename[2] = Browser(self.panel_scrolled, -1)
        self.button_AddFile = wx.Button(self, -1, _("Add a file"))

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.onAutodetect, self.button_Auto)
        self.Bind(wx.EVT_BUTTON, self.onAddFile, self.button_AddFile)
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: Panel_Files.__set_properties
        self.button_Auto.SetDefault()
        self.panel_scrolled.SetScrollRate(10, 10)
        # end wxGlade
        self.choice_pattern.AppendItems([apply(BIB.PATTERN[i],([BIB.NAME_FIELD[i] for i in BIB.BIB_FIELDS],)) for i in xrange(len(BIB.PATTERN))])
        self.choice_pattern.Select(0)

    def __do_layout(self):
        # begin wxGlade: Panel_Files.__do_layout
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_3.Add(self.button_Auto, 1, wx.ALL|wx.EXPAND, 5)
        sizer_3.Add(self.label_1, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_3.Add(self.choice_pattern, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_1.Add(sizer_3, 0, wx.EXPAND, 0)
        sizer_2.Add(self.filename[0], 1, wx.EXPAND, 0)
        sizer_2.Add(self.filename[1], 1, wx.EXPAND, 0)
        sizer_2.Add(self.filename[2], 1, wx.EXPAND, 0)
        self.panel_scrolled.SetSizer(sizer_2)
        sizer_1.Add(self.panel_scrolled, 1, wx.EXPAND, 0)
        sizer_1.Add(self.button_AddFile, 0, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        # end wxGlade
        self.sizerScroll = sizer_2          

    def onAutodetect(self, event): # wxGlade: Panel_Files.<event_handler>
        # setting the search pattern
        pattern = apply(BIB.PATTERN[self.choice_pattern.GetCurrentSelection()],(self.GetGrandParent().getCurrentRef(),))
        nullpattern = apply(BIB.PATTERN[self.choice_pattern.GetCurrentSelection()],(['']*len(BIB.BIB_FIELDS),))
        if pattern == nullpattern:    # If the reference is empty (NewRef), the pattern is ".*.*.*" and will return
            return                    # all the files in the directory
        #print pattern
        # we want a case-insensitive search to match both Einstein1920.pdf and EINSTEIN.pdf
        # We thus cannot use glob or fnmatch which are case-sensitive under linux
        # We do the match "by hand" using re module
        tmp = []
        for root, dirpaths, files in os.walk(BIB.FILES):
            for f in files:
                if re.search(pattern,f,re.I): tmp.append( os.path.join(root,f) )
        
        # getting current list of files then removing the already present files
        tmpf = self.getFiles()

        for i in xrange(len(tmp)-1,-1,-1):    # wwe must go top-down because deletion will change list length
            if tmp[i] in tmpf: del tmp[i]
        
        # filling boxes
        self.setFiles( tmp )

    def onAddFile(self, event): # wxGlade: Panel_Files.<event_handler>
        self.filename.append( Browser(self.panel_scrolled, -1) )
        self.sizerScroll.Add(self.filename[-1], 1, wx.EXPAND, 0)
        #self.panel_scrolled.Layout()
        self.Layout()
        
    def setFirstURL(self,url):
        """This is used to synchronize the URL fields from tab 1-3 with the first field in this page"""
        self.filename[0].SetValue(url)
        
    def setFiles(self,refs):
        # The first field since it is set from the URL field
        tmpf = []
        for field in self.filename:
            if not field.GetValue(): tmpf.append( field )
        for i in xrange( len(refs) - len(tmpf) ):
            self.onAddFile(None)
            tmpf.append( self.filename[-1] )
        #
        refs = list(refs)
        for i in xrange(len(refs)):
            if refs[i].startswith(BIB.FILES):    # We replace the default directory with $FILES
                refs[i] = refs[i].replace(BIB.FILES,'$FILES',1)
            tmpf[i].SetValue( refs[i] )
        
    def getFiles(self):
        """Return list of file paths. The first path is always returned even when empty since it is the URL field"""
        tmp=[self.filename[0].GetValue()]
        for fn in self.filename[1:]:
            if fn.GetValue(): tmp.append( fn.GetValue() )
        return tmp

# end of class Panel_Files


