# -*- coding: utf-8 -*-

# Copyright (c) 2004 - 2006 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing a dialog to search for files.
"""

import os
import sys

from qt import *

from FindFileNameForm import FindFileNameForm
from Utilities import direntries


class FindFileNameDialog(FindFileNameForm):
    """
    Class implementing a dialog to search for files.
    
    The occurences found are displayed in a QListView widget showing the
    filename and the pathname. The file will be opened upon a double click
    onto the respective entry of the list.
    
    @signal pythonFile(string) emitted to open a file in the editor
    @signal designerFile(string) emitted to open a Qt-Designer file
    """
    def __init__(self, project, parent = None):
        """
        Constructor
        
        @param project reference to the project object
        @param parent parent widget of this dialog (QWidget)
        """
        FindFileNameForm.__init__(self,parent)
        
        self.project = project
        self.extsepLabel.setText(os.extsep)

    def handleOpen(self):
        """
        Private slot to handle the double click and the Open button press. 
        
        It emits the signal
        pythonFile or designerFile depending on the file extension.
        """
        itm = self.fileView.currentItem()
        fileName = unicode(itm.text(0))
        filePath = unicode(itm.text(1))
        
        if fileName.endswith('.ui'):
            self.emit(PYSIGNAL('designerFile'),
                (os.path.join(filePath, fileName),))
        elif fileName.endswith('.ui.h'):
            fn = os.path.splitext(fileName)
            self.emit(PYSIGNAL('designerFile'),
                (os.path.join(filePath, fn),))
        else:
            self.emit(PYSIGNAL('pythonFile'),
                (os.path.join(filePath, fileName),))

    def searchFile(self):
        """
        Private slot to handle the search.
        """
        qApp.processEvents()
        
        fileName = unicode(self.fileNameEdit.text())
        if not fileName:
            return
        fileExt = unicode(self.fileExtEdit.text())
        fileNamePattern = "%s*%s%s" % (fileName, os.extsep,
            fileExt and fileExt or '*')
            
        searchPaths = []
        if self.projectCheckBox.isChecked():
            searchPaths.append(self.project.ppath)
        if self.syspathCheckBox.isChecked():
            searchPaths.extend(sys.path)
            
        found = 0
        self.fileView.clear()
        locations = {}
        for path in searchPaths:
            if os.path.isdir(path):
                files = direntries(path, 1, fileNamePattern)
                if files:
                    found = 1
                    for file in files:
                        fp, fn = os.path.split(file)
                        if locations.has_key(fn):
                            if fp in locations[fn]:
                                continue
                            else:
                                locations[fn].append(fp)
                        else:
                            locations[fn] = [fp]
                        QListViewItem(self.fileView, fn, fp)
                    qApp.processEvents()
            
        del locations
        self.openButton.setEnabled(found)

    def show(self):
        """
        Overwritten method to enable/disable the project checkbox.
        """
        if self.project.isOpen():
            self.projectCheckBox.setEnabled(1)
            self.projectCheckBox.setChecked(1)
            self.syspathCheckBox.setChecked(0)
        else:
            self.projectCheckBox.setEnabled(0)
            self.projectCheckBox.setChecked(0)
            self.syspathCheckBox.setChecked(1)
        
        self.fileNameEdit.selectAll()
        self.fileNameEdit.setFocus()
        
        FindFileNameForm.show(self)

    def keyPressEvent(self, evt):
        """
        Protected slot to intercept the return key press.
        
        @param evt a key press event (QKeyEvent)
        """
        key = evt.key()
        if (key == Qt.Key_Enter or key == Qt.Key_Return) and \
            self.openButton.isEnabled() and self.fileView.selectedItem():
            self.openButton.animateClick()
        else:
            evt.ignore()
