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

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

"""
Module implementing a dialog to enter the parameters for eric3-doc.
"""

import sys
import os
import copy

from qt import *

from KdeQt import KQFileDialog

from EricdocConfigForm import EricdocConfigForm
import Utilities

from eric3config import getConfig

class EricdocConfigDialog(EricdocConfigForm):
    """
    Class implementing a dialog to enter the parameters for eric3-doc.
    """
    def __init__(self,ppath,parms = None,parent = None):
        """
        Constructor
        
        @param ppath project path of the current project (string)
        @param parms parameters to set in the dialog
        @param parent parent widget of this dialog
        """
        EricdocConfigForm.__init__(self,parent)
        
        self.initializeDefaults()
        
        # get a copy of the defaults to store the user settings
        self.parameters = copy.deepcopy(self.defaults)
        
        # combine it with the values of parms
        if parms is not None:
            for key, value in parms.items():
                self.parameters[key] = parms[key]
        
        self.ppath = ppath
        
        self.prefixEdit.setText(self.parameters['filenamePrefix'])
        self.recursionCheckBox.setChecked(self.parameters['useRecursion'])
        self.noindexCheckBox.setChecked(self.parameters['noindex'])
        self.noemptyCheckBox.setChecked(self.parameters['noempty'])
        self.outputDirEdit.setText(self.parameters['outputDirectory'])
        self.ignoreDirsListBox.clear()
        for d in self.parameters['ignoreDirectories']:
            self.ignoreDirsListBox.insertItem(d)
        self.cssEdit.setText(self.parameters['cssFile'])
        self.sourceExtEdit.setText(", ".join(self.parameters['sourceExtensions']))

    def initializeDefaults(self):
        """
        Private method to set the default values. 
        
        These are needed later on to generate the commandline
        parameters.
        """
        self.defaults = {
            'filenamePrefix' : '',
            'useRecursion' : 0,
            'noindex' : 0,
            'noempty' : 0,
            'outputDirectory' : '',
            'ignoreDirectories' : [],
            'cssFile' : '',
            'sourceExtensions' : [],
        }
        
    def generateParameters(self):
        """
        Public method that generates the commandline parameters.
        
        It generates a QStringList to be used
        to set the QProcess arguments for the ericdoc call and
        a list containing the non default parameters. The second
        list can be passed back upon object generation to overwrite
        the default settings.
        
        @return a tuple of the commandline parameters and non default parameters
            (QStringList, dictionary)
        """
        parms = {}
        args = QStringList()
        
        # 1. the program name
        args.append(sys.executable)
        args.append(Utilities.normabsjoinpath(getConfig('ericDir'), "eric3-doc.py"))
        
        # 2. the commandline options
        if self.parameters['outputDirectory'] != self.defaults['outputDirectory']:
            parms['outputDirectory'] = self.parameters['outputDirectory']
            args.append('-o')
            if os.path.isabs(self.parameters['outputDirectory']):
                args.append(self.parameters['outputDirectory'])
            else:
                args.append(os.path.join(self.ppath, self.parameters['outputDirectory']))
        if self.parameters['ignoreDirectories'] != self.defaults['ignoreDirectories']:
            parms['ignoreDirectories'] = self.parameters['ignoreDirectories'][:]
            for d in self.parameters['ignoreDirectories']:
                args.append('-x')
                args.append(d)
        if self.parameters['filenamePrefix'] != self.defaults['filenamePrefix']:
            parms['filenamePrefix'] = self.parameters['filenamePrefix']
            args.append('-p')
            args.append(self.parameters['filenamePrefix'])
        if self.parameters['useRecursion'] != self.defaults['useRecursion']:
            parms['useRecursion'] = self.parameters['useRecursion']
            args.append('-r')
        if self.parameters['noindex'] != self.defaults['noindex']:
            parms['noindex'] = self.parameters['noindex']
            args.append('-i')
        if self.parameters['noempty'] != self.defaults['noempty']:
            parms['noempty'] = self.parameters['noempty']
            args.append('-e')
        if self.parameters['cssFile'] != self.defaults['cssFile']:
            parms['cssFile'] = self.parameters['cssFile']
            args.append('-c')
            if os.path.isabs(self.parameters['cssFile']):
                args.append(self.parameters['cssFile'])
            else:
                args.append(os.path.join(self.ppath, self.parameters['cssFile']))
        if self.parameters['sourceExtensions'] != self.defaults['sourceExtensions']:
            parms['sourceExtensions'] = self.parameters['sourceExtensions'][:]
            for ext in self.parameters['sourceExtensions']:
                args.append('-t')
                args.append(ext)
        
        return (args, parms)

    def handleOutputDir(self):
        """
        Private slot to select the output directory.
        
        It displays a directory selection dialog to
        select the directory the documentations is written to.
        """
        directory = KQFileDialog.getExistingDirectory(self.outputDirEdit.text(),
            self, None, self.trUtf8("Select output directory"))
            
        if not directory.isNull():
            # make it relative, if it is a subdirectory of the project path 
            dn = unicode(QDir.convertSeparators(directory))
            dn = dn.replace(self.ppath+os.sep, '')
            while dn.endswith(os.sep):
                dn = dn[:-1]
            self.outputDirEdit.setText(dn)

    def handleIgnoreDir(self):
        """
        Private slot to select a directory to be ignored.
        
        It displays a directory selection dialog to
        select a directory to be ignored.
        """
        directory = KQFileDialog.getExistingDirectory(self.ignoreDirEdit.text(),
            self, None, self.trUtf8("Select directory to exclude"), 1, 0)
            
        if not directory.isNull():
            # make it relative, if it is a subdirectory of the project path 
            dn = unicode(QDir.convertSeparators(directory))
            dn = dn.replace(self.ppath+os.sep, '')
            while dn.endswith(os.sep):
                dn = dn[:-1]
            self.ignoreDirEdit.setText(dn)

    def handleIgnoreDirAdd(self):
        """
        Private slot to add the directory displayed to the listview.
        
        The directory in the ignore directories
        line edit is moved to the listbox above and the edit is cleared.
        """
        self.ignoreDirsListBox.insertItem(os.path.basename(unicode(self.ignoreDirEdit.text())))
        self.ignoreDirEdit.clear()

    def handleIgnoreDirDelete(self):
        """
        Private slot to delete the currently selected directory of the listbox.
        """
        self.ignoreDirsListBox.removeItem(self.ignoreDirsListBox.currentItem())

    def handleCSSFile(self):
        """
        Private slot to select a css style sheet.
        """
        cssFile = KQFileDialog.getOpenFileName(\
            getConfig('ericCSSDir'),
            self.trUtf8("Style sheet (*.css);;All files (*)"),
            None, None,
            self.trUtf8("Select CSS style sheet"),
            None, 1)
            
        if not cssFile.isEmpty():
            # make it relative, if it is in a subdirectory of the project path 
            cf = unicode(QDir.convertSeparators(cssFile))
            cf = cf.replace(self.ppath+os.sep, '')
            self.cssEdit.setText(cf)

    def accept(self):
        """
        Protected slot called by the Ok button. 
        
        It saves the values in the parameters dictionary.
        """
        self.parameters['filenamePrefix'] = unicode(self.prefixEdit.text())
        self.parameters['useRecursion'] = self.recursionCheckBox.isChecked()
        self.parameters['noindex'] = self.noindexCheckBox.isChecked()
        self.parameters['noempty'] = self.noemptyCheckBox.isChecked()
        outdir = unicode(self.outputDirEdit.text())
        if outdir != '':
            outdir = os.path.normpath(outdir)
            if outdir.endswith(os.sep):
                outdir = outdir[:-1]
        self.parameters['outputDirectory'] = outdir
        itm = self.ignoreDirsListBox.firstItem()
        self.parameters['ignoreDirectories'] = []
        while itm is not None:
            self.parameters['ignoreDirectories'].append(\
                os.path.normpath(unicode(itm.text())))
            itm = itm.next()
        cssFile = unicode(self.cssEdit.text())
        if cssFile != '':
            cssFile = os.path.normpath(cssFile)
        self.parameters['cssFile'] = cssFile
        extensions = unicode(self.sourceExtEdit.text()).split(',')
        self.parameters['sourceExtensions'] = []
        for ext in extensions:
            self.parameters['sourceExtensions'].append(ext.strip())
        
        # call the accept slot of the base class
        EricdocConfigForm.accept(self)
