import string

from PyQt4 import QtGui, QtCore
from models.match_set_index import MatchSetIndex
from models.match_set import MatchSet

HEADER = ['Match Name',
          'Author(s)',
          'Focus Common %',
          'Match Common %',
          'Match Count']

COLUMNS = ['file_name',
           'edition',
           'alpha_match_pct',
           'beta_match_pct',
           'match_count']

COLUMN_TT = [u'Name of file',
             u'',
             u'Percentage of focus that is a match',
             u'Percentage of other document that is a match',
             u'Number of matching passages']


class MainTable(QtGui.QTableWidget):
    """
    Creates a table that self populates
    """

    def _set_header_tooltips(self):
        for i in xrange(len(COLUMN_TT)):
            header_item = self.horizontalHeaderItem(i)
            tool_tip = COLUMN_TT[i]
            header_item.setToolTip(tool_tip)

    def _set_initial_column_widths(self):
        self.setColumnWidth(0, 200)
        self.setColumnWidth(1, 100)
        self.setColumnWidth(2, 130)
        self.setColumnWidth(3, 130)
        self.setColumnWidth(4, 100)

    def _set_fonts(self):
        # Header and cell fonts
        font = QtGui.QFont('', 11, QtGui.QFont.Bold)
        self.horizontalHeader().setFont(font)
        cell_font = QtGui.QFont('', 11, QtGui.QFont.AnyStyle)
        self.setFont(cell_font)

    def __init__(self, parent=None):
        super(MainTable, self).__init__(parent)
        self.setColumnCount(5)
        self._set_initial_column_widths()
        self.horizontalHeader().setStretchLastSection(True)
        self.setAlternatingRowColors(True)
        self.setHorizontalHeaderLabels(HEADER)
        self.setSortingEnabled(True)

        self._set_fonts()
        self._set_header_tooltips()

    def populate(self, focus_name, msi):
        """
        Populates the table with metadata
        """

        match_set_list = msi.get_all_match_sets(focus_name=focus_name)
        cols = len(COLUMNS)
        self.setRowCount(len(match_set_list))
        self.setColumnCount(cols)

        # TODO: should use matchsets as entries, not documents
        #       otherwise we don't have the info we need
        for i, match_set in enumerate(match_set_list):
            meta = match_set.get_beta_metadata()
            for j, col_name in enumerate(COLUMNS):
                item = QtGui.QTableWidgetItem(j)
                uni_val = unicode(meta[col_name])
                item.setText(uni_val)
                item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.setItem(i, j, item)

    def _get_matchset_list(self, focus_doc, output_dir):
        """
        List of all matches found to the focus
        :param match_file: the match file
        :param entries: the list to append to
        """
        msi = MatchSetIndex(output_dir)
        self.focus = str(focus_doc)
        matchset_list = msi.get_all_match_sets(self.focus)
        return matchset_list

    def _get_sorted_metadata(self, metadata):
        sorted_metadata = []
        title = metadata.get('title')
        author = metadata.get('author')
        match_len = metadata.get('match_len')
        match_percent = metadata.get('match_percent')
        path = metadata.get('path')
        sorted_metadata.extend([title, author, match_len, match_percent, path])
        return sorted_metadata
@@ -1,19 +1,4 @@
-import string%0A%0A
 from
@@ -77,46 +77,8 @@
 ndex
-%0Afrom models.match_set import MatchSet
 %0A%0AHE
@@ -491,32 +491,32 @@
 at is a match',%0A
-
              u'N
@@ -546,16 +546,454 @@
 ges'%5D%0A%0A%0A
+class NumericalTableWidgetItem(QtGui.QTableWidgetItem):%0A    def __lt__(self, other):%0A        if isinstance(other, QtGui.QTableWidgetItem):%0A            my_value, my_ok = self.data(QtCore.Qt.EditRole).toFloat()%0A            other_value, other_ok = other.data(QtCore.Qt.EditRole).toFloat()%0A%0A            if my_ok and other_ok:%0A                return my_value %3C other_value%0A%0A        return super(NumericalTableWidgetItem, self).__lt__(other)%0A%0A%0A
 class Ma
@@ -2759,89 +2759,355 @@
     
-item = QtGui.QTableWidgetItem(j)%0A                uni_val = unicode(meta%5Bcol_name%5D
+uni_val = unicode(meta%5Bcol_name%5D)%0A                if j %3E= 3:%0A                    # Numerical columns%0A                    # TODO HACK%0A                    item = NumericalTableWidgetItem(j)%0A                    item.setData(QtCore.Qt.EditRole, QtCore.QVariant(float(uni_val)))%0A                else:%0A                    item = QtGui.QTableWidgetItem(j
 )%0A  

fix number sorting in results table