import os
from qtpy import QtWidgets
from qtpy import QtCore
from qtpy import QtGui
from ..utils import extract_filename
from .mplcontroller import MplController


class WaterfallTableController(object):

    def __init__(self, model, widget):
        self.model = model
        self.widget = widget
        self.plot_ctrl = MplController(self.model, self.widget)

    def _apply_changes_to_graph(self, reinforced=False):
        """
        this does not do actual nomalization but the processing.
        actual normalization takes place in plotting.
        """
        if reinforced:
            pass
        else:
            if not self.model.waterfall_exist():
                return
            count = 0
            for ptn in self.model.waterfall_ptn:
                if ptn.display:
                    count += 1
            if count == 0:
                return
        self.plot_ctrl.update()

    def update(self):
        """
        show a list of jcpds in the list window of tab 3
        called from maincontroller
        """
        n_columns = 2
        n_rows = self.model.waterfall_ptn.__len__()  # count for number of jcpds
        self.widget.tableWidget_wfPatterns.setColumnCount(n_columns)
        self.widget.tableWidget_wfPatterns.setRowCount(n_rows)
        self.widget.tableWidget_wfPatterns.horizontalHeader().setVisible(True)
        self.widget.tableWidget_wfPatterns.setHorizontalHeaderLabels(
            ['', ''])
        self.widget.tableWidget_wfPatterns.setVerticalHeaderLabels(
            [extract_filename(wfp.fname) for wfp in self.model.waterfall_ptn])
        for row in range(n_rows):
            # column 0 - checkbox
            item0 = QtWidgets.QTableWidgetItem()
            item0.setFlags(QtCore.Qt.ItemIsUserCheckable |
                           QtCore.Qt.ItemIsEnabled)
            if self.model.waterfall_ptn[row].display:
                item0.setCheckState(QtCore.Qt.Checked)
            else:
                item0.setCheckState(QtCore.Qt.Unchecked)
            self.widget.tableWidget_wfPatterns.setItem(row, 0, item0)
            # column 1 - color
            item2 = QtWidgets.QTableWidgetItem('')
            item2.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
            self.widget.tableWidget_wfPatterns.setItem(row, 1, item2)
            self.widget.tableWidget_wfPatterns.item(row, 1).setBackground(
                QtGui.QColor(self.model.waterfall_ptn[row].color))
        self.widget.tableWidget_wfPatterns.resizeColumnsToContents()
#        self.widget.tableWidget_wfPatterns.resizeRowsToContents()
        try:
            self.widget.tableWidget_wfPatterns.itemClicked.disconnect(
                self._handle_ItemClicked)
        except Exception:
            pass
        self.widget.tableWidget_wfPatterns.itemClicked.connect(
            self._handle_ItemClicked)
        # self._apply_changes_to_graph(reinforced=True)

    def _handle_ItemClicked(self, item):
        idx = item.row()
        if item.column() == 0:
            box_checked = (item.checkState() == QtCore.Qt.Checked)
            if box_checked == self.model.waterfall_ptn[idx].display:
                return
            self.model.waterfall_ptn[idx].display = box_checked
            self._apply_changes_to_graph(reinforced=True)
            return
        if item.column() == 1:
            color = QtWidgets.QColorDialog.getColor(
                QtGui.QColor(self.model.waterfall_ptn[idx].color))
            if color.isValid():
                self.widget.tableWidget_wfPatterns.item(idx, 1).setBackground(color)
                self.model.waterfall_ptn[idx].color = str(color.name())
                self._apply_changes_to_graph()
