from ..Qt import QtWidgets, QtCore, QtGui
from .._py.typeconversion import Ui_Dialog


class ConversionDialog(QtWidgets.QDialog, Ui_Dialog):
    convertSets = QtCore.pyqtSignal(list)

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)

        self.simple_table.installEventFilter(self)
        self.merge_table.installEventFilter(self)

        self._simple_table_dropevent = self.simple_table.dropEvent
        self.simple_table.dropEvent = self._drop_on_simple_table

        self._merge_table_dropevent = self.merge_table.dropEvent
        self.merge_table.dropEvent = self._drop_on_simple_table

        self.buttonGroup.buttonClicked.connect(self.change_table)

    def set_graphs(self, graphs: dict):
        self.set_list.clear()
        self.simple_table.clear()
        self.simple_table.setHorizontalHeaderLabels(['Simple', 'Type'])
        self.merge_table.clear()
        self.merge_table.setHorizontalHeaderLabels(['Real', 'Imag', 'Type'])

        for graph, datasets in graphs.items():
            for set_id, set_name in datasets:
                item_name = set_name + ' (' + graph[1] + ')'

                item1 = QtWidgets.QListWidgetItem(item_name)
                item1.setData(QtCore.Qt.UserRole, set_id)
                item1.setData(QtCore.Qt.UserRole+1, graph[0])
                self.set_list.addItem(item1)

    def eventFilter(self, src: QtCore.QObject, evt: QtCore.QEvent):
        if evt.type() in [QtCore.QEvent.DragEnter, QtCore.QEvent.DragMove]:
            evt.accept()
            return True

        if evt.type() == QtCore.QEvent.KeyPress and evt.key() == QtCore.Qt.Key_Delete:
            if src == self.simple_table:
                type_idx = 1
            else:
                type_idx = 2

            if len(src.selectedIndexes()) > 0:
                idx = src.selectedIndexes()[0]
                row, col = idx.row(), idx.column()

                if col != type_idx:
                    src.takeItem(row, col)
                    is_empty = all(src.item(row, i) is None for i in range(type_idx))
                    if is_empty:
                        src.removeRow(row)

                return True

        return super().eventFilter(src, evt)

    def _drop_on_simple_table(self, evt: QtGui.QDropEvent):
        """
        event filter does not receive dropevents?
        """
        if self.stackedWidget.currentIndex() == 0:
            table = self.simple_table
            type_column = 1
            default_drop = self._simple_table_dropevent
            type_name = ['Points', 'FID', 'Spectrum', 'BDS']
        else:
            table = self.merge_table
            type_column = 2
            default_drop = self._merge_table_dropevent
            type_name = ['FID', 'Spectrum', 'BDS']

        pos = evt.pos()
        drop_col = table.columnAt(pos.x())
        if drop_col == type_column:
            evt.ignore()
        else:
            drop_row = table.rowAt(pos.y())
            default_drop(evt)

            if drop_row == -1:
                w = QtWidgets.QComboBox()
                w.addItems(type_name)
                item = QtWidgets.QTableWidgetItem('')
                drop_row = table.rowAt(pos.y())
                table.setItem(drop_row, type_column, item)
                table.setCellWidget(drop_row, type_column, w)

            item = table.item(drop_row, drop_col)
            idx = table.indexFromItem(item)

            if idx.row() == -1 and idx.column() == -1:
                item = table.takeItem(drop_row, 0)
                table.setItem(drop_row, drop_col, item)

            if item is not None:
                item.setToolTip(item.text())

            table.resizeColumnsToContents()

    @QtCore.pyqtSlot(QtWidgets.QAbstractButton)
    def change_table(self, button: QtWidgets.QAbstractButton):
        idx = [self.simple_button, self.merge_button].index(button)
        self.stackedWidget.setCurrentIndex(idx)

    def collect_args(self) -> list:
        src_sets = []
        for row in range(self.simple_table.rowCount()):
            item = self.simple_table.item(row, 0)
            set_id = item.data(QtCore.Qt.UserRole)
            graph_id = item.data(QtCore.Qt.UserRole+1)
            type_idx = self.simple_table.cellWidget(row, 1).currentIndex()

            src_sets.append((set_id, graph_id, type_idx))

        for row in range(self.merge_table.rowCount()):
            item = self.merge_table.item(row, 0)
            graph_id = ''
            if item is not None:
                set_id_real = item.data(QtCore.Qt.UserRole)
                graph_id = item.data(QtCore.Qt.UserRole+1)
            else:
                set_id_real = ''

            item = self.merge_table.item(row, 1)
            if item is not None:
                set_id_imag = item.data(QtCore.Qt.UserRole)
                graph_id = item.data(QtCore.Qt.UserRole+1) if graph_id == '' else graph_id
            else:
                set_id_imag = ''
            type_idx = self.merge_table.cellWidget(row, 2).currentIndex() + 1

            src_sets.append((set_id_real, set_id_imag, graph_id, type_idx))

        self.convertSets.emit(src_sets)

        return src_sets

    @QtCore.pyqtSlot(QtWidgets.QAbstractButton, name='on_buttonBox_clicked')
    def button_clicked(self, button):
        role = self.buttonBox.buttonRole(button)
        if role == self.buttonBox.RejectRole:
            self.close()
        else:
            self.collect_args()
            self.accept()
