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

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

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

import sys
import os
import types

from qt import *

from TabnannyForm import TabnannyForm
import Tabnanny
import Utilities

class TabnannyDialog(TabnannyForm):
    """
    Class implementing a dialog to show the results of the tabnanny check run.
    """
    def __init__(self, viewmanager, parent = None):
        """
        Constructor
        
        @param viewmanager A reference to the viewmanager object.
        @param parent The parent widget (QWidget).
        """
        TabnannyForm.__init__(self, parent)
        
        self.vm = viewmanager
        self.noResults = 1
        self.cancelled = 0
        
    def start(self, fn):
        """
        Public slot to start the tabnanny check.
        
        @param fn File or list of files or directory to be checked
                (string or list of strings)
        """
        if type(fn) is types.ListType:
            files = fn
        elif os.path.isdir(fn):
            files = Utilities.direntries(fn, 1, '*.py', 0)
        else:
            files = [fn]
        
        self.checkProgress.setTotalSteps(len(files))
        qApp.processEvents()
        
        # now go through all the files
        progress = 0
        for file in files:
            if self.cancelled:
                return
            
            ok, fname, line, error = Tabnanny.check(file)
            if ok:
                self.noResults = 0
                itm = QListViewItem(self.resultList,
                    fname, line, `error.rstrip()`[1:-1])
            progress += 1
            self.checkProgress.setProgress(progress)
            qApp.processEvents()
                    
        self.finish()
        
    def finish(self):
        """
        Private slot called when the action or the user pressed the button.
        """
        self.cancelled = 1
        self.cancelButton.setText(self.trUtf8('OK'))
        self.cancelButton.setDefault(1)
        
        if self.noResults:
            itm = QListViewItem(self.resultList,
                self.trUtf8('No indentation errors found.'))
        
    def buttonPressed(self):
        """
        Private slot connected to the button clicked signal.
        """
        if self.cancelled:
            self.close()
        else:
            self.finish()
            
    def openFile(self, itm):
        """
        Private slot to handle the doubleClicked signal of the result list.
        
        @param itm The listview item that was double clicked.
        """
        if self.noResults:
            return
            
        fn = Utilities.normabspath(unicode(itm.text(0)))
        lineno = int(str(itm.text(1)))
        
        self.vm.handlePythonFile(fn, lineno)
