from ..Qt import QtCore, QtWidgets
from .._py.move_dialog import Ui_MoveDialog


class QMover(QtWidgets.QDialog, Ui_MoveDialog):
    moveData = QtCore.pyqtSignal(list, str, str)
    copyData = QtCore.pyqtSignal(list, str)

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

        self.entries = {}

        self.fromcomboBox.currentIndexChanged.connect(self.change_graph)
        self.buttonBox.clicked.connect(self.button_clicked)

    def setup(self, entries: dict):
        self.fromcomboBox.blockSignals(True)
        self.tocomboBox.blockSignals(True)
        for k, v in entries.items():
            self.entries[k[0]] = v
            self.fromcomboBox.addItem(k[1], userData=k[0])
            self.tocomboBox.addItem(k[1], userData=k[0])
        self.fromcomboBox.blockSignals(False)
        self.tocomboBox.blockSignals(False)
        self.change_graph(0)

    @QtCore.pyqtSlot(int)
    def change_graph(self, idx: int):
        self.listWidget.clear()
        idd = self.fromcomboBox.itemData(idx)
        if idd is not None:
            for i, j in self.entries[idd]:
                it = QtWidgets.QListWidgetItem(j)
                it.setData(QtCore.Qt.UserRole, i)
                self.listWidget.addItem(it)

    @QtCore.pyqtSlot(QtWidgets.QAbstractButton)
    def button_clicked(self, btn: QtWidgets.QAbstractButton):
        if self.buttonBox.buttonRole(btn) in [QtWidgets.QDialogButtonBox.ApplyRole,
                                              QtWidgets.QDialogButtonBox.AcceptRole]:
            from_graph = self.fromcomboBox.itemData(self.fromcomboBox.currentIndex())
            to_graph = self.tocomboBox.itemData(self.tocomboBox.currentIndex())
            if from_graph != to_graph:
                moving = []
                for idx in self.listWidget.selectedIndexes():
                    it = self.listWidget.itemFromIndex(idx)
                    moving.append(it.data(QtCore.Qt.UserRole))
                    it_data = (it.data(QtCore.Qt.UserRole), it.text())
                    if self.move_button.isChecked():
                        self.entries[from_graph].remove(it_data)
                    self.entries[to_graph].append(it_data)
                self.change_graph(self.fromcomboBox.currentIndex())

                if self.move_button.isChecked():
                    self.moveData.emit(moving, to_graph, from_graph)
                else:
                    self.copyData.emit(moving, to_graph)

            if self.buttonBox.buttonRole(btn) == QtWidgets.QDialogButtonBox.AcceptRole:
                self.close()

        elif self.buttonBox.buttonRole(btn) == QtWidgets.QDialogButtonBox.RejectRole:
            self.close()
        else:
            return

    def close(self):
        self.listWidget.clear()
        self.tocomboBox.clear()
        self.fromcomboBox.clear()
        self.entries = {}

        super().close()
