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

# Copyright (c) 2002, 2003 Detlev Offenbach <detlev@die-offenbachs.de>
#
#
# It is inspired by the cvs history form code found in LinCVS
#

"""
Module implementing a dialog to show the output of the cvs history command process.
"""

from qt import *

from HistoryForm import HistoryForm

class CvsHistoryDialog(HistoryForm):
    """
    Module implementing a dialog to show the output of the cvs history command process.
    """
    def __init__(self, vcs, parent = None):
        """
        Constructor
        
        Arguments
        
            vcs -- reference to the vcs object
            
            parent -- parent widget (QWidget)
        """
        HistoryForm.__init__(self, parent)
        
        self.setWFlags(self.getWFlags() | Qt.WDestructiveClose)
        self.process = QProcess(self)
        self.vcs = vcs
        self.index = 0
        
        self.connect(self.process, SIGNAL('readyReadStdout()'),
            self.handleReadStdout)
        self.connect(self.process, SIGNAL('readyReadStderr()'),
            self.handleReadStderr)
        self.connect(self.process, SIGNAL('processExited()'),
            self.handleProcessExited)
            
    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, fn):
        """
        Public slot to start the cvs history command.
        
        Arguments
        
            fn -- filename (string)
        """
        self.filename = fn
        self.dname, self.fname = self.vcs.splitPath(fn)
        
        self.process.kill()
        
        self.process.clearArguments()
        self.process.addArgument('cvs')
        self.vcs.addArguments(self.process, self.vcs.options['global'])
        self.process.addArgument('history')
        self.vcs.addArguments(self.process, self.vcs.options['history'])
        self.process.addArgument(self.fname)
        self.process.setWorkingDirectory(QDir(self.dname))
        
        self.process.start()
        self.setCaption(self.trUtf8('CVS History %1').arg(self.filename))
        
    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 is not None and \
                self.process.canReadLineStdout():
            s = self.process.readLineStdout()
            
            if s.isEmpty():
                continue
                
            list = QStringList.split(' ',s)
            cmd = str(list[0])
            if len(cmd) != 1:
                continue    # we got something 
                
            if cmd in ['O', 'F', 'E']:
                if list.count() != 8:
                    continue # we got some bad output
                ncol = 8
                if str(self.fname) != '.':
                    continue
            else:
                if list.count() != 10:
                    continue # we got some bad output
                ncol = 10
                dir = str(list[7])
                if str(self.dname)[-len(dir):] != dir:
                    continue
                
            if cmd == 'O':
                event = self.trUtf8('Checkout ')
            elif cmd == 'T':
                event = self.trUtf8('Tag ')
            elif cmd == 'F':
                event = self.trUtf8('Release ')
            elif cmd == 'E':
                event = self.trUtf8('Export ')
            elif cmd == 'W':
                event = self.trUtf8('Update, Deleted ')
            elif cmd == 'U':
                event = self.trUtf8('Update, Copied ')
            elif cmd == 'G':
                event = self.trUtf8('Update, Merged ')
            elif cmd == 'C':
                event = self.trUtf8('Update, Conflict ')
            elif cmd == 'M':
                event = self.trUtf8('Commit, Modified ')
            elif cmd == 'A':
                event = self.trUtf8('Commit, Added ')
            elif cmd == 'R':
                event = self.trUtf8('Commit, Removed ')
            else:
                event = self.trUtf8('Unknown')
                
            if ncol == 10:
                QListViewItem(self.historyList, '%05d' % self.index,
                    ' %s %s %s ' % (str(list[1]), str(list[2]), str(list[3])),
                    event, list[4], list[5], list[6], list[7])
            else:
                QListViewItem(self.historyList, '%05d' % self.index,
                    ' %s %s %s ' % (str(list[1]), str(list[2]), str(list[3])),
                    event, list[4], '', '', list[5])
                    
            self.index += 1
        
    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 is not None and \
                self.process.canReadLineStderr():
            s = self.process.readLineStderr()
            self.errors.append(s)
