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

# Copyright (c) 2002 - 2007 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 PyQt4.QtCore import *
from PyQt4.QtGui import *

from Ui_CvsHistoryDialog import Ui_CvsHistoryDialog

class CvsHistoryDialog(QWidget, Ui_CvsHistoryDialog):
    """
    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)
        """
        QWidget.__init__(self, parent)
        self.setupUi(self)
        
        self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(True)
        
        self.process = QProcess()
        self.vcs = vcs
        self.index = 0
        
        self.connect(self.process, SIGNAL('finished(int, QProcess::ExitStatus)'),
            self.__procFinished)
        self.connect(self.process, SIGNAL('readyReadStandardOutput()'),
            self.__readStdout)
        self.connect(self.process, SIGNAL('readyReadStandardError()'),
            self.__readStderr)
        
    def __resort(self):
        """
        Private method to resort the tree.
        """
        self.historyList.sortItems(self.historyList.sortColumn(), 
            self.historyList.header().sortIndicatorOrder())
        
    def __resizeColumns(self):
        """
        Private method to resize the list columns.
        """
        self.historyList.header().resizeSections(QHeaderView.ResizeToContents)
        self.historyList.header().setStretchLastSection(True)
        
    def __generateItem(self, index, date, time, timezone, event, author, revision,
                       file, path):
        """
        Private method to generate a status item in the status list.
        
        @param index index number of the history entry (integer)
        @param date date of the entry (string or QString)
        @param time time of the entry (string or QString)
        @param timezone timezone of the entry (string or QString)
        @param event event type (string or QString)
        @param author author (string or QString)
        @param revision revision number (string or QString)
        @param file file name (string or QString)
        @param path path of the file (string or QString)
        """
        itm = QTreeWidgetItem(self.historyList, 
            QStringList() \
            << '%05d' % index \
            << ' %s %s %s ' % (unicode(date), unicode(time), unicode(timezone)) \
            << event \
            << author \
            << revision \
            << file \
            << path
        )
        
    def closeEvent(self, e):
        """
        Private slot implementing a close event handler.
        
        @param e close event (QCloseEvent)
        """
        if self.process is not None and \
           self.process.state() != QProcess.NotRunning:
            self.process.terminate()
            QTimer.singleShot(2000, self.process, SLOT('kill()'))
            self.process.waitForFinished(3000)
        
        e.accept()
        
    def start(self, fn):
        """
        Public slot to start the cvs history command.
        
        @param fn filename (string)
        """
        self.setWindowTitle(self.trUtf8('CVS History %1').arg(fn))
        QApplication.processEvents()
        
        self.intercept = False
        self.filename = fn
        self.dname, self.fname = self.vcs.splitPath(fn)
        
        self.process.kill()
        
        args = QStringList()
        self.vcs.addArguments(args, self.vcs.options['global'])
        args.append('history')
        self.vcs.addArguments(args, self.vcs.options['history'])
        args.append(self.fname)
        
        self.process.setWorkingDirectory(self.dname)
        
        self.process.start('cvs', args)
        
    def __finish(self):
        """
        Private slot called when the process finished or the user pressed the button.
        """
        if self.process is not None and \
           self.process.state() != QProcess.NotRunning:
            self.process.terminate()
            QTimer.singleShot(2000, self.process, SLOT('kill()'))
            self.process.waitForFinished(3000)
        
        self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True)
        self.buttonBox.button(QDialogButtonBox.Cancel).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Close).setDefault(True)
        
        self.inputGroup.setEnabled(False)
        
        self.process = None
        
        self.historyList.doItemsLayout()
        self.__resizeColumns()
        self.__resort()
        
    def on_buttonBox_clicked(self, button):
        """
        Private slot called by a button of the button box clicked.
        
        @param button button that was clicked (QAbstractButton)
        """
        if button == self.buttonBox.button(QDialogButtonBox.Close):
            self.close()
        elif button == self.buttonBox.button(QDialogButtonBox.Cancel):
            self.__finish()
        
    def __procFinished(self, exitCode, exitStatus):
        """
        Private slot connected to the finished signal.
        
        @param exitCode exit code of the process (integer)
        @param exitStatus exit status of the process (QProcess.ExitStatus)
        """
        self.__finish()
        
    def __readStdout(self):
        """
        Private slot to handle the readyReadStdout signal.
        
        It reads the output of the process, formats it and inserts it into
        the contents pane.
        """
        self.process.setReadChannel(QProcess.StandardOutput)
        
        while self.process.canReadLine():
            s = QString(self.process.readLine())
            
            if s.isEmpty():
                continue
            
            list = s.split(' ', QString.SkipEmptyParts)
            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 == 'P':
                event = self.trUtf8('Update, Patched')
                
            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 (%1)').arg(cmd)
            
            if ncol == 10:
                self.__generateItem(self.index, list[1], list[2], list[3], event, 
                    list[4], list[5], list[6], list[7])
            else:
                self.__generateItem(self.index, list[1], list[2], list[3], event, 
                    list[4], '', '', list[5])
            
            self.index += 1
        
    def __readStderr(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 = QString(self.process.readAllStandardError())
            self.errors.insertPlainText(s)
            self.errors.ensureCursorVisible()
        
    def on_passwordCheckBox_toggled(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)
        
    @pyqtSignature("")
    def on_sendButton_clicked(self):
        """
        Private slot to send the input to the subversion process.
        """
        input = self.input.text()
        input.append(os.linesep)
        
        if self.passwordCheckBox.isChecked():
            self.errors.insertPlainText(os.linesep)
            self.errors.ensureCursorVisible()
        else:
            self.errors.insertPlainText(input)
            self.errors.ensureCursorVisible()
        
        self.proc.write(input.toLocal8Bit())
        
        self.passwordCheckBox.setChecked(False)
        self.input.clear()
        
    def on_input_returnPressed(self):
        """
        Private slot to handle the press of the return key in the input field.
        """
        self.intercept = True
        self.on_sendButton_clicked()
        
    def keyPressEvent(self, evt):
        """
        Protected slot to handle a key press event.
        
        @param evt the key press event (QKeyEvent)
        """
        if self.intercept:
            self.intercept = False
            evt.accept()
            return
        QWidget.keyPressEvent(self, evt)
