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

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

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

import sys
import os
import copy

from qt import *

from KdeQt import KQFileDialog

from EricapiConfigForm import EricapiConfigForm
import Utilities

from eric3config import getConfig

class EricapiConfigDialog(EricapiConfigForm):
    """
    Class implementing a dialog to enter the parameters for eric3-api.
    """
    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
        """
        EricapiConfigForm.__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.recursionCheckBox.setChecked(self.parameters['useRecursion'])
        self.newStyleCheckBox.setChecked(self.parameters['newStyle'])
        self.outputFileEdit.setText(self.parameters['outputFile'])
        self.baseEdit.setText(self.parameters['basePackage'])
        self.ignoreDirsListBox.clear()
        for d in self.parameters['ignoreDirectories']:
            self.ignoreDirsListBox.insertItem(d)
        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 = {
            'useRecursion' : 0,
            'newStyle' : 0,
            'outputFile' : '',
            'basePackage' : '',
            'ignoreDirectories' : [],
            '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 ericapi 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-api.py"))
        
        # 2. the commandline options
        if self.parameters['outputFile'] != self.defaults['outputFile']:
            parms['outputFile'] = self.parameters['outputFile']
            args.append('-o')
            if os.path.isabs(self.parameters['outputFile']):
                args.append(self.parameters['outputFile'])
            else:
                args.append(os.path.join(self.ppath, self.parameters['outputFile']))
        if self.parameters['basePackage'] != self.defaults['basePackage']:
            parms['basePackage'] = self.parameters['basePackage']
            args.append('-b')
            args.append(self.parameters['basePackage'])
        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['useRecursion'] != self.defaults['useRecursion']:
            parms['useRecursion'] = self.parameters['useRecursion']
            args.append('-r')
        if self.parameters['sourceExtensions'] != self.defaults['sourceExtensions']:
            parms['sourceExtensions'] = self.parameters['sourceExtensions'][:]
            for ext in self.parameters['sourceExtensions']:
                args.append('-t')
                args.append(ext)
        if self.parameters['newStyle'] != self.defaults['newStyle']:
            parms['newStyle'] = self.parameters['newStyle']
            args.append('--newstyle')
        
        return (args, parms)

    def handleOutputFile(self):
        """
        Private slot to select the output file.
        
        It displays a file selection dialog to
        select the file the api is written to.
        """
        filename = KQFileDialog.getSaveFileName(self.outputFileEdit.text(),
            QString.null, self, None, self.trUtf8("Select output file"))
            
        if not filename.isNull():
            # make it relative, if it is in a subdirectory of the project path 
            fn = unicode(QDir.convertSeparators(filename))
            fn = fn.replace(self.ppath+os.sep, '')
            self.outputFileEdit.setText(fn)

    def handleFileChanged(self, filename):
        """
        Private slot to enable/disable the "OK" button.
        
        @param filename name of the file (QString)
        """
        self.okButton.setEnabled(not filename.isEmpty())

    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 accept(self):
        """
        Protected slot called by the Ok button. 
        
        It saves the values in the parameters dictionary.
        """
        self.parameters['useRecursion'] = self.recursionCheckBox.isChecked()
        self.parameters['newStyle'] = self.newStyleCheckBox.isChecked()
        outfile = unicode(self.outputFileEdit.text())
        if outfile != '':
            outfile = os.path.normpath(outfile)
        self.parameters['outputFile'] = outfile
        self.parameters['basePackage'] = unicode(self.baseEdit.text())
        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()
        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
        EricapiConfigForm.accept(self)
