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

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

"""
Package implementing interfaces to packaging tools.

It implements the high level interface and all the supporting dialogs
for the supported packagers.
"""

import sys
import os.path
import shutil

from qt import *

from KdeQt import KQMessageBox

from CxfreezeConfigDialog import CxfreezeConfigDialog
from PackagersExecDialog import PackagersExecDialog

from UI.E3Action import E3Action, E3ActionGroup

import Utilities


class Packagers(QObject):
    """ 
    Class implementing the high level interface.
    """
    def __init__(self, project, parent):
        """
        Constructor
        
        @param project project object of the current project
        @param parent parent object of this class (QObject)
        """
        QObject.__init__(self, parent)
        
        self.project = project
        self.actions = []
        
    def initActions(self):
        """
        Private method to initialize the packagers actions.
        """
        self.actions = []
        
        self.cxfreezeAct = E3Action(self.trUtf8('Use cx_Freeze'),
            self.trUtf8('Use cx_&Freeze'),0,0,self,'packagers_cxfreeze')
        self.cxfreezeAct.setStatusTip(\
            self.trUtf8('Generate a distribution package using cx_Freeze'))
        self.cxfreezeAct.setWhatsThis(self.trUtf8(
            """<b>Use cx_Freeze</b>"""
            """<p>Generate a distribution package using cx_Freeze."""
            """ The command is executed in the project path. All"""
            """ files and directories must be given absolute or"""
            """ relative to the project directory.</p>"""
        ))
        self.cxfreezeAct.connectIt(SIGNAL('activated()'),self.handleCxfreeze)
        self.actions.append(self.cxfreezeAct)
        
    def initMenu(self):
        """
        Private method called to build the project packagers submenu.
        
        @return the menu or None
        """
        menu = QPopupMenu(self.parent())
        
        self.cxfreezeAct.addTo(menu)
        
        # entry for cxfreeze is only activated if it is accessible
        exe = 'FreezePython'
        if sys.platform == "win32":
            exe += '.exe'
        self.cxfreezeAct.setEnabled(Utilities.isinpath(exe))
        
        return menu
        
    def handleCxfreeze(self):
        """
        Private slot to handle the cxfreeze execution.
        """
        if len(self.project.pdata["MAINSCRIPT"]) == 0:
            # no main script defined
            KQMessageBox.critical(None,
                self.trUtf8("FreezePython"),
                self.trUtf8("""There is no main script defined for the current project."""),
                self.trUtf8("&Abort"),
                QString.null,
                QString.null,
                0, -1)
            return
        
        if len(self.project.pdata['CXFREEZEPARMS']):
            parms = eval(self.project.pdata['CXFREEZEPARMS'][0])
        else:
            parms = None
        dlg = CxfreezeConfigDialog(self.project.ppath, parms)
        if dlg.exec_loop() == QDialog.Accepted:
            args, parms = dlg.generateParameters()
            
            # test for changes of selected parameters and save them in the project
            # 1. there were none, now there are
            if len(self.project.pdata['CXFREEZEPARMS']) == 0 and len(parms) > 0:
                self.project.pdata['CXFREEZEPARMS'] = [unicode(parms)]
                self.project.setDirty(1)
            # 2. there were some, now there aren't
            elif len(self.project.pdata['CXFREEZEPARMS']) > 0 and len(parms) == 0:
                self.project.pdata['CXFREEZEPARMS'] = []
                self.project.setDirty(1)
            # 3. there were some and still are
            else:
                sparms = unicode(parms)
                if sparms != self.project.pdata['CXFREEZEPARMS'][0]:
                    self.project.pdata['CXFREEZEPARMS'] = [sparms]
                    self.project.setDirty(1)
                    
            # now do the call
            dia = PackagersExecDialog("FreezePython")
            dia.show()
            res = dia.start(args, 
                os.path.join(self.project.ppath, self.project.pdata["MAINSCRIPT"][0]))
            if res:
                dia.exec_loop()
        
    def getActions(self):
        """
        Public method to get a list of all actions.
        
        @return list of all actions (list of E3Action)
        """
        return self.actions[:]
