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

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

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

from qt import *

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
        
        Arguments
        
            vcs -- reference to the vcs object
            
            parent -- parent widget (QWidget)
        """
        TagBranchListForm.__init__(self, parent)
        
        self.setWFlags(self.getWFlags() | Qt.WDestructiveClose)
        self.process = QProcess(self)
        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_list = QRegExp('\\w\\s+(\\d+)\\s+(\\w+)\\s+\\d+\\s+(\\w+ \\d+ \\d+:\\d+)\\s+(.+)/')
        # _       4   detlev        0 Jun 27 17:46 tag_1/
            
    def closeEvent(self, e):
        """
        Private slot implementing a close event handler.
        
        Arguments
        
            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.
        
        Arguments
        
            path -- name of directory to be listed (string)
            
            tags -- flag indicating a list of tags is requested
                (0 = branches, 1 = tags)
        """
        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:
            QMessageBox.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"),
                None,
                None,
                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')
        if reposURL.startswith('http'):
            self.vcs.addArguments(self.process, self.vcs.authData())
        self.setActiveWindow()
        
        # determine the base path of the project in the repository
        rx_base = QRegExp('(.+)/(trunk|tags|branches).*')
        if not rx_base.exactMatch(reposURL):
            QMessageBox.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"),
                None,
                None,
                0,-1)
            return
            
        reposRoot = str(rx_base.cap(1))
        
        if tags:
            self.process.addArgument("%s/tags" % reposRoot)
        else:
            self.process.addArgument("%s/branches" % reposRoot)
        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.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_list.exactMatch(s):
                rev = self.rx_list.cap(1)
                author = self.rx_list.cap(2)
                date = self.rx_list.cap(3)
                path = self.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.
        """
        while self.process.canReadLineStderr():
            s = self.process.readLineStderr()
            self.errors.append(s)
