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

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

"""
Module implementing a code metrics dialog.
"""

import sys
import os
import types

from qt import *

from CodeMetricsForm import CodeMetricsForm
import CodeMetrics
import Utilities

class CodeMetricsDialog(CodeMetricsForm):
    """
    Class implementing a dialog to display the code metrics.
    """
    def __init__(self, parent = None):
        """
        Constructor
        
        @param parent parent widget (QWidget)
        """
        CodeMetricsForm.__init__(self, parent)
        
        self.resultList.setSorting(-1)
        self.summaryList.setSorting(-1)
        
        for col in range(1,7):
            self.resultList.setColumnAlignment(col, Qt.AlignRight)
        self.summaryList.setColumnAlignment(1, Qt.AlignRight)
        
        self.cancelled = 0
        
    def start(self, fn):
        """
        Public slot to start the code metrics determination.
        
        @param fn file or list of files or directory to be show
                the code metrics for (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]
        files.sort()
        files.reverse()
        # check for missing files
        for f in files[:]:
            if not os.path.exists(f):
                files.remove(f)
        
        self.checkProgress.setTotalSteps(len(files))
        qApp.processEvents()
        
        total = {}
        CodeMetrics.summarize(total, 'files', len(files))
        
        # now go through all the files
        progress = 0
        for file in files:
            if self.cancelled:
                return
            
            fitm = QListViewItem(self.resultList, file)
            fitm.setOpen(1)
            
            stats = CodeMetrics.analyze(file, total)
                
            identifiers = stats.identifiers + ['TOTAL ']
            identifiers.reverse()
            for id in identifiers:
                counters = stats.counters.get(id, {})
                v = []
                for key in ('start', 'end', 'lines', 'nloc', 'comments', 'empty'):
                    if counters.get(key, 0):
                        v.append(str(counters[key]))
                    else:
                        v.append('')
                        
                itm = QListViewItem(fitm, id, v[0], v[1], v[2], v[3], v[4], v[5])
                
            progress += 1
            self.checkProgress.setProgress(progress)
            qApp.processEvents()
            
        # now do the summary stuff
        docstrings = total['lines'] - total['comments'] - total['empty lines'] - total['non-commentary lines']
        itm = QListViewItem(self.summaryList, self.trUtf8("documentation lines"), str(docstrings))
        itm = QListViewItem(self.summaryList, self.trUtf8("non-commentary lines"), str(total['non-commentary lines']))
        itm = QListViewItem(self.summaryList, self.trUtf8("empty lines"), str(total['empty lines']))
        itm = QListViewItem(self.summaryList, self.trUtf8("comments"), str(total['comments']))
        itm = QListViewItem(self.summaryList, self.trUtf8("bytes"), str(total['bytes']))
        itm = QListViewItem(self.summaryList, self.trUtf8("lines"), str(total['lines']))
        itm = QListViewItem(self.summaryList, self.trUtf8("files"), str(total['files']))
        
        self.finish()
        
    def finish(self):
        """
        Private slot called when the action finished or the user pressed the button.
        """
        self.cancelled = 1
        self.cancelButton.setText(self.trUtf8('OK'))
        self.cancelButton.setDefault(1)
        
    def buttonPressed(self):
        """
        Private slot connected to the button clicked signal.
        """
        if self.cancelled:
            self.close()
        else:
            self.finish()
