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

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

"""
Module implementing a dialog to show the results of the PyLint run.
"""

import sys
import os

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from KdeQt import KQMessageBox, KQFileDialog
from KdeQt.KQApplication import e4App

from Ui_PyLintExecDialog import Ui_PyLintExecDialog

import Preferences
import Utilities

class PyLintExecDialog(QWidget, Ui_PyLintExecDialog):
    """
    Class implementing a dialog to show the results of the PyLint run.
    
    This class starts a QProcess and displays a dialog that
    shows the results of the PyLint command process.
    """
    def __init__(self, parent = None):
        """
        Constructor
        
        @param parent parent widget of this dialog (QWidget)
        """
        QWidget.__init__(self, parent)
        self.setupUi(self)
        
        self.saveButton = self.buttonBox.addButton(\
            self.trUtf8("Save Report..."), QDialogButtonBox.ActionRole)
        self.saveButton.setToolTip(\
            self.trUtf8("Press to save the report to a file"))
        self.saveButton.setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(True)
        
        self.messageList.header().setSortIndicator(0, Qt.AscendingOrder)
        
        self.process = None
        self.noResults = True
        self.htmlOutput = False
        self.parsedOutput = False
        
        self.typeDict = {
            'C' : self.trUtf8('Convention'),
            'R' : self.trUtf8('Refactor'),
            'W' : self.trUtf8('Warning'),
            'E' : self.trUtf8('Error'),
            'F' : self.trUtf8('Fatal'),
        }
        
    def start(self, args, fn, reportFile, ppath):
        """
        Public slot to start PyLint.
        
        @param args commandline arguments for documentation programPyLint (QStringList)
        @param fn filename or dirname to be processed by PyLint
        @param reportFile filename of file to write the report to (string or QString)
        @param ppath project path (string or QString)
        @return flag indicating the successful start of the process
        """
        self.reportFile = reportFile
        self.ppath = ppath
        
        self.pathname = os.path.dirname(unicode(fn))
        self.filename = os.path.basename(unicode(fn))
        
        self.contents.clear()
        self.errors.clear()
        self.saveButton.setEnabled(False)
        
        program = args[0]
        del args[0]
        args.append(self.filename)
        
        self.process = QProcess()
        self.process.setWorkingDirectory(self.pathname)
        
        self.connect(self.process, SIGNAL('readyReadStandardError()'),
            self.__readStderr)
        self.connect(self.process, SIGNAL('finished(int, QProcess::ExitStatus)'),
            self.__finish)
            
        if args.contains("--output-format=parseable"):
            self.__ioEncoding = str(Preferences.getSystem("IOEncoding"))
            self.reportFile = None
            self.contents.hide()
            self.connect(self.process, SIGNAL('readyReadStandardOutput()'),
                self.__readParseStdout)
            self.parsedOutput = True
        else:
            self.connect(self.process, SIGNAL('readyReadStandardOutput()'),
                self.__readStdout)
            self.messageList.hide()
            if args.contains("--output-format=html"):
                self.contents.setAcceptRichText(True)
                self.contents.setHtml('<b>Processing your request...</b>')
                self.htmlOutput = True
            else:
                self.contents.setAcceptRichText(False)
                self.contents.setCurrentFont(\
                    Preferences.getEditorOtherFonts("MonospacedFont"))
                self.htmlOutput = False
            self.parsedOutput = False
        self.noResults = True
        
        self.buf = QString("")
        
        self.process.start(program, args)
        procStarted = self.process.waitForStarted()
        if not procStarted:
            KQMessageBox.critical(None,
                self.trUtf8('Process Generation Error'),
                self.trUtf8(
                    'The process %1 could not be started. '
                    'Ensure, that it is in the search path.'
                ).arg(program))
        else:
            self.setCursor(QCursor(Qt.WaitCursor))
        return procStarted
        
    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()
        elif button == self.saveButton:
            self.on_saveButton_clicked()
        
    def __finish(self):
        """
        Private slot called when the process finished.
        
        It is called when the process finished or
        the user pressed the button.
        """
        self.unsetCursor()
        
        if self.htmlOutput:
            self.contents.setHtml(self.buf)
        else:
            cursor = self.contents.textCursor()
            cursor.movePosition(QTextCursor.Start)
            self.contents.setTextCursor(cursor)
        
        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)
        if self.parsedOutput:
            QApplication.processEvents()
            self.messageList.sortItems(self.messageList.sortColumn(), 
                                       self.messageList.header().sortIndicatorOrder())
            self.messageList.header().resizeSections(QHeaderView.ResizeToContents)
            self.messageList.header().setStretchLastSection(True)
        
        self.process = None
        
        if self.reportFile:
            self.__writeReport()
        elif not self.parsedOutput:
            self.saveButton.setEnabled(True)
        
        if self.noResults:
            self.__createItem(self.trUtf8('No PyLint errors found.'), "", "", "")
        
    def __readStdout(self):
        """
        Private slot to handle the readyReadStandardOutput 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 = self.process.readLine()
            self.buf.append(s).append(os.linesep)
            if not self.htmlOutput:
                self.contents.insertPlainText(QString(s))
                self.contents.ensureCursorVisible()
        
    def __createItem(self, file, line, type_, message):
        """
        Private method to create an entry in the message list.
        
        @param file filename of file (string or QString)
        @param line linenumber of message (integer or string)
        @param type_ type of message (string or QString)
        @param message message text (string or QString)
        """
        itm = QTreeWidgetItem(self.messageList, QStringList() \
            << file << str(line) << type_ << message)
        itm.setTextAlignment(1, Qt.AlignRight)
        itm.setTextAlignment(2, Qt.AlignHCenter)
        
    def __readParseStdout(self):
        """
        Private slot to handle the readyReadStandardOutput signal for parseable output. 
        
        It reads the output of the process, formats it and inserts it into
        the message list pane.
        """
        self.process.setReadChannel(QProcess.StandardOutput)
        
        while self.process.canReadLine():
            s = unicode(self.process.readLine(), self.__ioEncoding, 'replace')
            if s:
                try:
                    if sys.platform == "win32":
                        drive, s = os.path.splitdrive(s)
                        fname, lineno, fullmessage = s.split(':')
                        fname = drive + fname
                    else:
                        fname, lineno, fullmessage = s.split(':')
                    type_, message = fullmessage.strip().split(']', 1)
                    type_ = type_.strip()[1]
                    message = message.strip()
                    if self.typeDict.has_key(type_):
                        self.__createItem(fname, lineno, self.typeDict[type_], message)
                        self.noResults = False
                except ValueError:
                    continue
        
    def __readStderr(self):
        """
        Private slot to handle the readyReadStandardError signal. 
        
        It reads the error output of the process and inserts it into the
        error pane.
        """
        self.process.setReadChannel(QProcess.StandardError)
        
        while self.process.canReadLine():
            s = QString(self.process.readLine())
            self.errors.insertPlainText(s)
            self.errors.ensureCursorVisible()
        
    def on_messageList_itemActivated(self, itm, column):
        """
        Private slot to handle the itemActivated signal of the message list.
        
        @param itm The message item that was activated (QTreeWidgetItem)
        @param column column the item was activated in (integer)
        """
        if self.noResults:
            return
        
        fn = os.path.join(self.pathname, unicode(itm.text(0)))
        lineno = int(str(itm.text(1)))
        
        e4App().getObject("ViewManager").openSourceFile(fn, lineno)
        
    def __writeReport(self):
        """
        Private slot to write the report to a report file.
        """
        self.reportFile = unicode(self.reportFile)
        if os.path.exists(self.reportFile):
            res = KQMessageBox.warning(self,
                self.trUtf8("PyLint Report"),
                self.trUtf8(\
                    """<p>The PyLint report file <b>%1</b> already exists.</p>""")\
                    .arg(self.reportFile),
                QMessageBox.StandardButtons(\
                    QMessageBox.Cancel | \
                    QMessageBox.Ignore),
                QMessageBox.Cancel)
            if res == QMessageBox.Cancel:
                return
        
        try:
            f = open(self.reportFile, 'wb')
            f.write(unicode(self.buf))
            f.close()
        except IOError, why:
            KQMessageBox.critical(self, self.trUtf8('PyLint Report'),
                self.trUtf8('<p>The PyLint report file <b>%1</b> could not be written.'
                            '<br>Reason: %2</p>')
                    .arg(self.reportFile).arg(str(why)))
        
    @pyqtSignature("")
    def on_saveButton_clicked(self):
        """
        Private slot to save the report to a file.
        """
        if self.htmlOutput:
            filter = self.trUtf8("HTML Files (*.html);;All Files (*)")
        else:
            filter = self.trUtf8("Text Files (*.txt);;All Files (*)")
        
        self.reportFile = KQFileDialog.getSaveFileName(\
            self,
            self.trUtf8("PyLint Report"),
            self.ppath,
            filter,
            None,
            QFileDialog.Options(QFileDialog.DontConfirmOverwrite))
        if not self.reportFile.isEmpty():
            self.__writeReport()
