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

# Copyright (c) 2002 - 2005 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.
"""

import os

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
        
        @param vcs reference to the vcs object
        @param parent parent widget (QWidget)
        """
        HistoryForm.__init__(self, parent)
        
        self.setWFlags(self.getWFlags() | Qt.WDestructiveClose)
        self.process = QProcess()
        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.
        
        @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, fn):
        """
        Public slot to start the cvs history command.
        
        @param fn filename (string)
        """
        self.intercept = 0
        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.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 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 unicode(self.fname) != '.':
                    continue
            else:
                if list.count() != 10:
                    continue # we got some bad output
                ncol = 10
                dir = unicode(list[7])
                if unicode(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 ' % (unicode(list[1]), unicode(list[2]), unicode(list[3])),
                    event, list[4], list[5], list[6], list[7])
            else:
                QListViewItem(self.historyList, '%05d' % self.index,
                    ' %s %s %s ' % (unicode(list[1]), unicode(list[2]), unicode(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.
        """
        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
        LogForm.keyPressEvent(self, evt)
