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

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

"""
Module implementing the project properties dialog.
"""

import os
import string

from qt import *

from KdeQt import KQFileDialog

from PropertiesForm import PropertiesForm
from VCS.Config import ConfigVcsSystems, ConfigVcsSystemsDisplay
from VCS.RepositoryInfoDialog import VcsRepositoryInfoDialog
import Preferences

class PropertiesDialog(PropertiesForm):
    """
    Class implementing the project properties dialog.
    """
    def __init__(self,project,new = 1,parent = None,name = None,modal = 0,fl = 0):
        """
        Constructor
        
        @param project reference to the project object
        @param new flag indicating the generation of a new project
        @param parent parent widget of this dialog (QWidget)
        @param name name of this dialog (string or QString)
        @param modal flag indicating a modal dialog
        @param fl window flags
        """
        PropertiesForm.__init__(self,parent,name,1,fl)
        
        self.project = project
        
        projectLanguages = QStringList()
        projectLanguages.append("Python")
        projectLanguages.append("Ruby")
        self.languageComboBox.insertStringList(projectLanguages)
        
        uiTypes = QStringList()
        for uiType in project.uiTypes:
            uiTypes.append(uiType[1]) # entry 1 is the display string
        self.uiTypeComboBox.insertStringList(uiTypes)
        
        if not new:
            (name, dummy) = os.path.splitext(self.project.pfile)
            self.nameEdit.setText(os.path.basename(name))
            self.languageComboBox.setCurrentText(self.project.pdata["PROGLANGUAGE"][0])
            self.mixedLanguageCheckBox.setChecked(self.project.pdata["MIXEDLANGUAGE"][0])
            for uiType in project.uiTypes:
                if uiType[0] == self.project.pdata["UITYPE"][0]:
                    self.uiTypeComboBox.setCurrentText(uiType[1])
                    break
            self.dirEdit.setText(self.project.ppath)
            try:
                self.versionEdit.setText(self.project.pdata["VERSION"][0])
            except IndexError:
                pass
            try:
                self.mainscriptEdit.setText(self.project.pdata["MAINSCRIPT"][0])
            except IndexError:
                pass
            try:
                self.transPrefixEdit.setText(os.path.join(\
                    self.project.ppath,self.project.pdata["TRANSLATIONPREFIX"][0]))
            except IndexError:
                pass            
            try:
                self.authorEdit.setText(self.project.pdata["AUTHOR"][0])
            except IndexError:
                pass
            try:
                self.emailEdit.setText(self.project.pdata["EMAIL"][0])
            except IndexError:
                pass
            try:
                self.descriptionEdit.setText(\
                    string.join(self.project.pdata["DESCRIPTION"], '\n'))
            except:
                pass
            self.vcsLabel.show()
            if self.project.vcs is not None:
                ind = ConfigVcsSystems.index(self.project.pdata["VCS"][0])
                self.vcsLabel.setText(\
                    self.trUtf8("The project is version controlled by <b>%1</b>.")
                    .arg(ConfigVcsSystemsDisplay[ind]))
                self.vcsInfoButton.show()
            else:
                self.vcsLabel.setText(\
                    self.trUtf8("The project is not version controlled."))
                self.vcsInfoButton.hide()
        else:
            hp = os.getcwd()
            hp = hp + os.sep
            self.dirEdit.setText(hp)
            self.versionEdit.setText('0.1')
            self.vcsLabel.hide()
            self.vcsInfoButton.hide()
        
    def handleDirDialog(self):
        """
        Private slot to display a directory selection dialog.
        """
        directory = KQFileDialog.getExistingDirectory(self.dirEdit.text(),
            self, None, self.trUtf8("Select project directory"), 1)
            
        if not directory.isNull():
            self.dirEdit.setText(QDir.convertSeparators(directory))
        
    def handleTransPrefixDialog(self):
        """
        Private slot to display a directory selection dialog.
        """
        directory = KQFileDialog.getExistingDirectory(self.transPrefixEdit.text(),
            self, None, self.trUtf8("Select project directory"), 1)
            
        if not directory.isNull():
            self.transPrefixEdit.setText(QDir.convertSeparators(directory))
        
    def handleFileDialog(self):
        """
        Private slot to display a file selection dialog.
        """
        dir = self.dirEdit.text()
        if dir.isEmpty():
            dir = QDir.currentDirPath()
        filters = QString(self.project.sourceFilters[str(self.languageComboBox.currentText())])
        filters.append(self.trUtf8("All Files (*)"))
        fn = KQFileDialog.getOpenFileName(dir, filters,
            self, None, self.trUtf8("Select main script file"))
            
        if not fn.isNull():
            ppath = self.dirEdit.text()
            if not ppath.isEmpty():
                ppath = QDir(ppath).absPath()
                ppath.append(QDir.separator())
                fn.replace(QRegExp(ppath), "")
            self.mainscriptEdit.setText(QDir.convertSeparators(fn))
        
    def handleShowVcsInfo(self):
        """
        Private slot to display a vcs information dialog.
        """
        if self.project.vcs is None:
            return
            
        info = self.project.vcs.vcsRepositoryInfos(self.project.ppath)
        dlg = VcsRepositoryInfoDialog(self, info)
        dlg.exec_loop()
        
    def storeData(self):
        """
        Public method to store the entered/modified data.
        """
        self.project.ppath = os.path.abspath(unicode(self.dirEdit.text()))
        fn = self.nameEdit.text()
        if not fn.isEmpty():
            self.project.name = unicode(fn)
            if Preferences.getProject("CompressedProjectFiles"):
                fn = "%s.e3pz" % unicode(fn)
            else:
                fn = "%s.e3p" % unicode(fn)
            self.project.pfile = os.path.join(self.project.ppath, fn)
        else:
            self.project.pfile = ""
        self.project.pdata["VERSION"] = [str(self.versionEdit.text())]
        fn = self.mainscriptEdit.text()
        if not fn.isEmpty():
            fn = unicode(fn).replace(self.project.ppath+os.sep, "")
            self.project.pdata["MAINSCRIPT"] = [fn]
            self.project.translationsRoot, dummy = os.path.splitext(fn)
        else:
            self.project.pdata["MAINSCRIPT"] = []
            self.project.translationsRoot = ""
        self.project.pdata["AUTHOR"] = [unicode(self.authorEdit.text())]
        self.project.pdata["EMAIL"] = [str(self.emailEdit.text())]
        text = unicode(self.descriptionEdit.text())
        self.project.pdata["DESCRIPTION"] = text.split('\n')
        self.project.pdata["PROGLANGUAGE"] = [str(self.languageComboBox.currentText())]
        self.project.pdata["MIXEDLANGUAGE"] = [self.mixedLanguageCheckBox.isChecked() and 1 or 0]
        for uiType in self.project.uiTypes:
            selectedUiType = self.uiTypeComboBox.currentText()
            if uiType[1].compare(selectedUiType) == 0:
                self.project.pdata["UITYPE"] = [uiType[0]]
                break
        tp = self.transPrefixEdit.text()
        if not tp.isEmpty():
            tp = unicode(tp).replace(self.project.ppath+os.sep, "")
            self.project.pdata["TRANSLATIONPREFIX"] = [tp]
            self.project.translationsRoot = tp
        else:
            self.project.pdata["TRANSLATIONPREFIX"] = []
