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

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

"""
Module implementing a dialog to show a list of tags or branches.
"""

from qt import *

from KdeQt import KQMessageBox, KQInputDialog

from TagBranchListForm import TagBranchListForm

class SvnTagBranchListDialog(TagBranchListForm):
    """
    Module implementing a dialog to show a list of tags or branches.
    """
    def __init__(self, vcs, parent = None):
        """
        Constructor
        
        @param vcs reference to the vcs object
        @param parent parent widget (QWidget)
        """
        TagBranchListForm.__init__(self, parent)
        
        self.setWFlags(self.getWFlags() | Qt.WDestructiveClose)
        self.process = QProcess()
        self.vcs = vcs
        
        self.tagList.setSorting(3)
        
        self.connect(self.process, SIGNAL('readyReadStdout()'),
            self.handleReadStdout)
        self.connect(self.process, SIGNAL('readyReadStderr()'),
            self.handleReadStderr)
        self.connect(self.process, SIGNAL('processExited()'),
            self.handleProcessExited)
            
        self.rx_list1 = QRegExp('\\w\\s+(\\d+)\\s+(\\w+)\\s+\\d+\\s+(\\w+ \\d+ \\d+:\\d+)\\s+(.+)/')
        # _       4   detlev        0 Jun 27 17:46 tag_1/
        self.rx_list2 = QRegExp('\\w\\s+(\\d+)\\s+(\\w+)\\s+\\d+\\s+(\\w+ \\d+  \\d+)\\s+(.+)/')
        # _       4   detlev        0 Jun 27 2003 tag_1/
        self.rx_list3 = QRegExp('\\s*(\\d+)\\s+(\\w+)\\s+\\d*\\s*(\\w+ \\d+ \\d+:\\d+)\\s+(.+)/')
        #        4   detlev        Jun 27 17:46 tag_1/
        self.rx_list4 = QRegExp('\\s*(\\d+)\\s+(\\w+)\\s+\\d*\\s*(\\w+ \\d+  \\d+)\\s+(.+)/')
        #        4   detlev        Jun 27 17:46 tag_1/
            
    def closeEvent(self, e):
        """
        Private slot implementing a close event handler.
        
        @param e close event (QCloseEvent)
        """
        if self.process is not None:
            self.process.tryTerminate()
            QTimer.singleShot(2000, self.process, SLOT('kill()'))
            
        e.accept()
        
    def start(self, path, tags = 1):
        """
        Public slot to start the svn status command.
        
        @param path name of directory to be listed (string)
        @param tags flag indicating a list of tags is requested
                (0 = branches, 1 = tags)
        """
        self.intercept = 0
        if not tags:
            self.setCaption(self.trUtf8("Subversion Branches List"))
            
        dname, fname = self.vcs.splitPath(path)
        
        self.process.kill()
        
        reposURL = self.vcs.svnGetReposName(dname)
        if reposURL is None:
            KQMessageBox.critical(None,
                self.trUtf8("Subversion Error"),
                self.trUtf8("""The URL of the project repository could not be"""
                    """ retrieved from the working copy. The list operation will"""
                    """ be aborted"""),
                self.trUtf8("OK"),
                QString.null,
                QString.null,
                0,-1)
            self.close()
            return
            
        self.process.clearArguments()
        self.process.addArgument('svn')
        self.process.addArgument('list')
        self.vcs.addArguments(self.process, self.vcs.options['global'])
        self.process.addArgument('--verbose')
        self.setActiveWindow()
        
        if self.vcs.otherData["standardLayout"]:
            # determine the base path of the project in the repository
            rx_base = QRegExp('(.+)/(trunk|tags|branches).*')
            if not rx_base.exactMatch(reposURL):
                KQMessageBox.critical(None,
                    self.trUtf8("Subversion Error"),
                    self.trUtf8("""The URL of the project repository has an"""
                        """ invalid format. The list operation will"""
                        """ be aborted"""),
                    self.trUtf8("OK"),
                    QString.null,
                    QString.null,
                    0,-1)
                return
                
            reposRoot = unicode(rx_base.cap(1))
            
            if tags:
                self.process.addArgument("%s/tags" % reposRoot)
            else:
                self.process.addArgument("%s/branches" % reposRoot)
        else:
            reposPath, ok = KQInputDialog.getText(\
                self.trUtf8("Subversion List"),
                self.trUtf8("Enter the repository URL containing the tags or branches"),
                QLineEdit.Normal,
                self.vcs.svnNormalizeURL(reposURL), self)
            if not ok:
                self.close()
                return
            if reposPath.isEmpty():
                KQMessageBox.critical(None,
                    self.trUtf8("Subversion List"),
                    self.trUtf8("""The repository URL is empty. Aborting..."""),
                    self.trUtf8("&OK"),
                    QString.null,
                    QString.null,
                    0, -1)
                self.close()
                return
            self.process.addArgument(reposPath)

        self.process.setWorkingDirectory(QDir(dname))
        
        self.process.start()
        
    def finish(self):
        """
        Private slot called when the process finished or the user pressed the button.
        """
        if self.process is not None:
            self.process.tryTerminate()
            QTimer.singleShot(2000, self.process, SLOT('kill()'))
            
        self.cancelButton.setText(self.trUtf8('OK'))
        self.cancelButton.setDefault(1)
        self.cancelButton.setFocus()
        
        self.inputGroup.setEnabled(0)
        
        self.process = None
        
    def buttonPressed(self):
        """
        Private slot connected to the button clicked signal.
        """
        if self.process is None:
            self.close()
        else:
            self.finish()
            
    def handleProcessExited(self):
        """
        Private slot to handle the processExited signal.
        
        Just call finish().
        """
        self.finish()
        
    def handleReadStdout(self):
        """
        Private slot to handle the readyReadStdout signal.
        
        It reads the output of the process, formats it and inserts it into
        the contents pane.
        """
        while self.process.canReadLineStdout():
            s = self.process.readLineStdout()
            if self.rx_list1.exactMatch(s):
                rx_list = self.rx_list1
            elif self.rx_list2.exactMatch(s):
                rx_list = self.rx_list2
            elif self.rx_list3.exactMatch(s):
                rx_list = self.rx_list3
            elif self.rx_list4.exactMatch(s):
                rx_list = self.rx_list4
            else:
                rx_list = None
            if rx_list:
                rev = "%6s" % unicode(rx_list.cap(1))
                author = rx_list.cap(2)
                date = rx_list.cap(3)
                path = rx_list.cap(4)
                itm = QListViewItem(self.tagList,
                    rev, author, date, path)
                
    def handleReadStderr(self):
        """
        Private slot to handle the readyReadStderr signal.
        
        It reads the error output of the process and inserts it into the
        error pane.
        """
        if self.process is not None:
            s = unicode(self.process.readStderr())
            self.errors.moveCursor(QTextEdit.MoveEnd, 0)
            self.errors.insert(s)
        
    def passwordMode(self, isOn):
        """
        Private slot to handle the password checkbox toggled.
        
        @param isOn flag indicating the status of the check box (boolean)
        """
        if isOn:
            self.input.setEchoMode(QLineEdit.Password)
        else:
            self.input.setEchoMode(QLineEdit.Normal)
        
    def sendInput(self):
        """
        Private slot to send the input to the subversion process.
        """
        input = self.input.text()
        input.append(os.linesep)
        
        self.errors.moveCursor(QTextEdit.MoveEnd, 0)
        if self.passwordCheckBox.isChecked():
            self.errors.insert(os.linesep)
        else:
            self.errors.insert(input)
        
        self.proc.writeToStdin(input)
        
        self.passwordCheckBox.setChecked(0)
        self.input.clear()
        
    def returnPressed(self):
        """
        Private slot to handle the press of the return key in the input field.
        """
        self.intercept = 1
        self.sendInput()
        
    def keyPressEvent(self, evt):
        """
        Protected slot to handle a key press event.
        
        @param evt the key press event (QKeyEvent)
        """
        if self.intercept:
            self.intercept = 0
            evt.accept()
            return
        TagBranchListForm.keyPressEvent(self, evt)
