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

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

"""
Module implementing a dialog to show the output of the svn diff command process.
"""

import os

from qt import *

from LogForm import LogForm

class SvnDiffDialog(LogForm):
    """
    Class implementing a dialog to show the output of the svn diff command process.
    """
    def __init__(self, vcs, parent = None):
        """
        Constructor
        
        Arguments
        
            vcs -- reference to the vcs object
            
            parent -- parent widget (QWidget)
        """
        LogForm.__init__(self, parent)
        
        self.contentsLabel.setText(self.trUtf8('Difference:'))
        self.setCaption(self.trUtf8('Subversion Diff'))
        QWhatsThis.add(self.contents,self.tr("<b>Subversion Diff</b>\n"
            "<p>This shows the output of the svn diff command.</p>"
        ))
        QWhatsThis.add(self.errors,self.tr("<b>Subversion diff errors</b>\n"
            "<p>This shows possible error messages of the svn diff"
            " command.</p>"
        ))
        
        self.setWFlags(self.getWFlags() | Qt.WDestructiveClose)
        self.process = QProcess(self)
        self.vcs = vcs
        
        self.cAdded = QColor(190, 237, 190)
        self.cRemoved = QColor(237, 190, 190)
        
        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, versions=None):
        """
        Public slot to start the svn diff command.
        
        Arguments
        
            fn -- filename to be diffed (string)
            
            versions -- list of versions to be diffed (list of 2 QString or None)
        """
        self.filename = fn
        dname, fname = self.vcs.splitPath(fn)
        
        self.process.kill()
        self.contents.clear()
        self.contents.setBold(0)
        
        self.process.clearArguments()
        self.process.addArgument('svn')
        self.process.addArgument('diff')
        self.vcs.addArguments(self.process, self.vcs.options['global'])
        self.vcs.addArguments(self.process, self.vcs.options['diff'])
        if versions is not None:
            try:
                if self.vcs.svnGetReposName(dname).startswith('http'):
                    self.vcs.addArguments(self.process, self.vcs.authData())
                self.setActiveWindow()
                self.raiseW()
            except:
                pass
            self.process.addArgument('-r')
            self.process.addArgument('%s:%s' % (str(versions[0]), str(versions[1])))
        self.process.addArgument(fname)
        self.process.setWorkingDirectory(QDir(dname))
        
        self.process.start()
        self.setCaption(self.trUtf8('Subversion Diff %1').arg(self.filename))
        
    def handleProcessExited(self):
        """
        Private slot to handle the processExited signal.
        
        After the process has exited, the contents pane is colored.
        """
        paras = self.contents.paragraphs()
        if paras == 1:
            self.contents.append(\
                self.trUtf8('There is no difference.'))
            return
            
        self.saveButton.setEnabled(1)
        for i in range(paras):
            txt = self.contents.text(i)
            if txt.length() > 0:
                if txt.startsWith('+') or txt.startsWith('>'):
                    self.contents.setParagraphBackgroundColor(i, self.cAdded)
                elif txt.startsWith('-') or txt.startsWith('<'):
                    self.contents.setParagraphBackgroundColor(i, self.cRemoved)
        
    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.
        """
        self.contents.setTextFormat(QTextBrowser.PlainText)
        
        while self.process.canReadLineStdout():
            s = self.process.readLineStdout()
            self.contents.append(s)
                
    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)
            
    def handleSave(self):
        """
        Private slot to handle the Save button press.
        
        It saves the diff shown in the dialog to a file in the local
        filesystem.
        """
        dname, fname = self.vcs.splitPath(self.filename)
        if fname != '.':
            fname = "%s.diff" % self.filename
        else:
            fname = dname
            
        selectedFilter = QString('')
        fname = QFileDialog.getSaveFileName(\
            self.trUtf8(fname),
            self.trUtf8("Patch Files (*.diff)"),
            self, None,
            self.trUtf8("Save Diff"),
            selectedFilter, 0)
        
        if fname.isEmpty():
            return
            
        ext = QFileInfo(fname).extension()
        if ext.isEmpty():
            ex = selectedFilter.section('(*',1,1).section(')',0,0)
            if not ex.isEmpty():
                fname.append(ex)
        if QFileInfo(fname).exists():
            abort = QMessageBox.warning(self,
                self.trUtf8("Save Diff"),
                self.trUtf8("The patch file <b>%1</b> already exists.")
                    .arg(fname),
                self.trUtf8("&Overwrite"),
                self.trUtf8("&Abort"), None, 1)
            if abort:
                return
        fname = str(QDir.convertSeparators(fname))
        
        try:
            f = open(fname, "wb")
            paras = self.contents.paragraphs()
            for i in range(paras):
                txt = self.contents.text(i)
                try:
                    f.write("%s%s" % (str(txt), os.linesep))
                except UnicodeError:
                    pass
            f.close()
        except IOError, why:
            QMessageBox.critical(self, self.trUtf8('Save Diff'),
                self.trUtf8('The patch file <b>%1</b> could not be saved.<br>Reason: %2')
                    .arg(fn).arg(str(why)))
