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

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

"""
Module implementing a dialog to enter the parameters for cxfreeze.
"""

import sys
import os
import copy

from qt import *

from KdeQt import KQFileDialog

from CxfreezeConfigForm import CxfreezeConfigForm
import Utilities

class CxfreezeConfigDialog(CxfreezeConfigForm):
    """
    Class implementing a dialog to enter the parameters for cxfreeze.
    """
    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
        """
        CxfreezeConfigForm.__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.exe = "FreezePython"
        if sys.platform == "win32":
            self.exe += '.exe'
        self.exePath = os.path.dirname(Utilities.getExecutablePath(self.exe))
        
        # populate combo boxes
        d = QDir(os.path.join(self.exePath, 'bases'))
        basesList = d.entryList(QDir.Files)
        basesList.prepend('')
        self.basenameCombo.insertStringList(basesList)
        
        d = QDir(os.path.join(self.exePath, 'initscripts'))
        initList = d.entryList('*.py')
        initList.prepend('')
        self.initscriptCombo.insertStringList(initList)
        
        # initialize general tab
        self.targetDirEdit.setText(self.parameters['targetDirectory'])
        self.targetNameEdit.setText(self.parameters['targetName'])
        self.basenameCombo.setCurrentText(self.parameters['baseName'])
        self.initscriptCombo.setCurrentText(self.parameters['initScript'])
        self.keeppathCheckBox.setChecked(self.parameters['keepPath'])
        self.optimizeGroup.setButton(self.parameters['optimize'])
        
        # initialize advanced tab
        self.sharedLibEdit.setText(self.parameters['sharedLib'])
        self.defaultPathEdit.setText(os.pathsep.join(self.parameters['defaultPath']))
        self.includePathEdit.setText(os.pathsep.join(self.parameters['includePath']))
        self.replacePathsEdit.setText(os.pathsep.join(self.parameters['replacePaths']))
        self.includeModulesEdit.setText(','.join(self.parameters['includeModules']))
        self.excludeModulesEdit.setText(','.join(self.parameters['excludeModules']))
        self.extListFileEdit.setText(self.parameters['extListFile'])

    def initializeDefaults(self):
        """
        Private method to set the default values. 
        
        These are needed later on to generate the commandline
        parameters.
        """
        self.defaults = {
            # general options
            'targetDirectory' : '',
            'targetName' : '',
            'baseName' : '',
            'initScript' : '',
            'keepPath' : 0,
            'optimize' : 0,     # 0, 1 or 2
            
            # advanced options
            'sharedLib' : '',
            'defaultPath' : [],
            'includePath' : [],
            'replacePaths' : [],
            'includeModules' : [],
            'excludeModules' : [],
            'extListFile' : '',
        }
        
    def generateParameters(self):
        """
        Public method that generates the commandline parameters.
        
        It generates a QStringList to be used
        to set the QProcess arguments for the cxfreeze 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(self.exe)
        
        # 2. the commandline options
        # 2.1 general options
        if self.parameters['targetDirectory'] != self.defaults['targetDirectory']:
            parms['targetDirectory'] = self.parameters['targetDirectory']
            args.append('--target-dir=%s' % self.parameters['targetDirectory'])
        if self.parameters['targetName'] != self.defaults['targetName']:
            parms['targetName'] = self.parameters['targetName'][:]
            args.append('--target-name=%s' % self.parameters['targetName'])
        if self.parameters['baseName'] != self.defaults['baseName']:
            parms['baseName'] = self.parameters['baseName'][:]
            args.append('--base-name=%s' % self.parameters['baseName'])
        if self.parameters['initScript'] != self.defaults['initScript']:
            parms['initScript'] = self.parameters['initScript'][:]
            args.append('--init-script=%s' % self.parameters['initScript'])
        if self.parameters['keepPath'] != self.defaults['keepPath']:
            parms['keepPath'] = self.parameters['keepPath']
            args.append('--keep-path')
        if self.parameters['optimize'] != self.defaults['optimize']:
            parms['optimize'] = self.parameters['optimize']
            if self.parameters['optimize'] == 1:
                args.append('-O')
            elif self.parameters['optimize'] == 2:
                args.append('-OO')
        
        # 2.2 advanced options
        if self.parameters['sharedLib'] != self.defaults['sharedLib']:
            parms['sharedLib'] = self.parameters['sharedLib']
            args.append('--shared-lib-name=%s' % self.parameters['sharedLib'])
        if self.parameters['defaultPath'] != self.defaults['defaultPath']:
            parms['defaultPath'] = self.parameters['defaultPath'][:]
            args.append('--default-path=%s' % os.pathsep.join(self.parameters['defaultPath']))
        if self.parameters['includePath'] != self.defaults['includePath']:
            parms['includePath'] = self.parameters['includePath'][:]
            args.append('--include-path=%s' % os.pathsep.join(self.parameters['includePath']))
        if self.parameters['replacePaths'] != self.defaults['replacePaths']:
            parms['replacePaths'] = self.parameters['replacePaths'][:]
            args.append('--replace-paths=%s' % os.pathsep.join(self.parameters['replacePaths']))
        if self.parameters['includeModules'] != self.defaults['includeModules']:
            parms['includeModules'] = self.parameters['includeModules'][:]
            args.append('--include-modules=%s' % ','.join(self.parameters['includeModules']))
        if self.parameters['excludeModules'] != self.defaults['excludeModules']:
            parms['excludeModules'] = self.parameters['excludeModules'][:]
            args.append('--exclude-modules=%s' % ','.join(self.parameters['excludeModules']))
        if self.parameters['extListFile'] != self.defaults['extListFile']:
            parms['extListFile'] = self.parameters['extListFile']
            args.append('--ext-list-file=%s' % self.parameters['extListFile'])
        
        return (args, parms)

    def handleTargetDir(self):
        """
        Private slot to select the target directory.
        
        It displays a directory selection dialog to
        select the directory the files are written to.
        """
        directory = KQFileDialog.getExistingDirectory(self.targetDirEdit.text(),
            self, None, self.trUtf8("Select target 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.targetDirEdit.setText(dn)

    def handleSharedLib(self):
        """
        Private slot to select the Python shared library.
        
        It displays a file selection dialog to select the Python shared library.
        """
        sharedLib = KQFileDialog.getOpenFileName(\
            self.sharedLibEdit.text(),
            QString.null,
            None, None,
            self.trUtf8("Select Python shared library"),
            None, 1)
            
        if not sharedLib.isEmpty():
            # make it relative, if it is in a subdirectory of the project path 
            sl = unicode(QDir.convertSeparators(sharedLib))
            sl = sl.replace(self.ppath+os.sep, '')
            self.sharedLibEdit.setText(sl)
    
    def handleExtListFile(self):
        """
        Private slot to select the external list file.
        
        It displays a file selection dialog to select the external list file,
        the list of include modules is written to.
        """
        extList = KQFileDialog.getOpenFileName(\
            self.extListFileEdit.text(),
            QString.null,
            None, None,
            self.trUtf8("Select external list file"),
            None, 1)
            
        if not extList.isEmpty():
            # make it relative, if it is in a subdirectory of the project path 
            lf = unicode(QDir.convertSeparators(extList))
            lf = lf.replace(self.ppath+os.sep, '')
            self.extListFileEdit.setText(lf)
    
    def accept(self):
        """
        Protected slot called by the Ok button. 
        
        It saves the values in the parameters dictionary.
        """
        # get data of general tab
        self.parameters['targetDirectory'] = unicode(self.targetDirEdit.text())
        self.parameters['targetName'] = unicode(self.targetNameEdit.text())
        self.parameters['baseName'] = unicode(self.basenameCombo.currentText())
        self.parameters['initScript'] = unicode(self.initscriptCombo.currentText())
        self.parameters['keepPath'] = self.keeppathCheckBox.isChecked()
        self.parameters['optimize'] = self.optimizeGroup.selectedId()
        
        # get data of advanced tab
        self.parameters['sharedLib'] = unicode(self.sharedLibEdit.text())
        self.parameters['defaultPath'] = \
            self.splitIt(unicode(self.defaultPathEdit.text()), os.pathsep)
        self.parameters['includePath'] = \
            self.splitIt(unicode(self.includePathEdit.text()), os.pathsep)
        self.parameters['replacePaths'] = \
            self.splitIt(unicode(self.replacePathsEdit.text()), os.pathsep)
        self.parameters['includeModules'] = \
            self.splitIt(unicode(self.includeModulesEdit.text()), ',')
        self.parameters['excludeModules'] = \
            self.splitIt(unicode(self.excludeModulesEdit.text()), ',')
        self.parameters['extListFile'] = unicode(self.extListFileEdit.text())
        
        # call the accept slot of the base class
        CxfreezeConfigForm.accept(self)

    def splitIt(self, s, sep):
        """
        Private method to split a string.
        
        It differs from Pythons implementation in the way, that it returns
        an empty list, if the split is attempted on an empty string.
        
        @param s string to split (string)
        @param sep separator string (string)
        @return list of split values
        """
        if s == "" or s is None:
            return []
        
        if s.endswith(sep):
            s = s[:-1]
        
        return s.split(sep)
