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


class InterpolDialog(QtWidgets.QDialog, Ui_Dialog):
    new_data = QtCore.pyqtSignal(list, str, bool, bool, tuple, str)

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

        self.src_widget.hide()
        validator = QtGui.QDoubleValidator()
        self.start_lineEdit.setValidator(validator)
        self.stop_lineEdit.setValidator(validator)
        self.step_lineEdit.setValidator(QtGui.QIntValidator())

        self._data = {}
        self._src_id = None
        self._dest_graph = ''

    def __call__(self):
        self.listWidget.clear()
        self._data = {}

    @QtCore.pyqtSlot(int,  name='on_xaxis_comboBox_currentIndexChanged')
    def change_x_source(self, idx: int):
        self.src_widget.setVisible(idx == 1)
        self.sampling_widget.setVisible(idx != 1)

    def set_data(self, data, current_gid):
        self.graph_combobox.blockSignals(True)
        self._data = {}
        dest_idx = 0
        for (gid, graph_name), sets in data.items():
            self.graph_combobox.addItem(graph_name, userData=gid)
            self.dest_combobox.addItem(graph_name, userData=gid)
            if self._dest_graph == gid:
                dest_idx = self.dest_combobox.currentIndex()
            if gid == current_gid:
                self.make_list(sets)
            self._data[gid] = sets
        self.graph_combobox.blockSignals(False)
        self.change_graph(dest_idx)

    def make_list(self, current_sets):
        for sid, set_name in current_sets:
            item = QtWidgets.QListWidgetItem(set_name)
            item.setData(QtCore.Qt.ItemDataRole.UserRole, sid)
            item.setCheckState(QtCore.Qt.CheckState.Checked)
            self.listWidget.addItem(item)

    @QtCore.pyqtSlot(int, name='on_graph_combobox_currentIndexChanged')
    def change_graph(self, idx: int):
        self.set_combobox.clear()
        gid = self.graph_combobox.itemData(idx, QtCore.Qt.ItemDataRole.UserRole)
        set_idx = -1
        if gid is not None:
            for i, (set_key, set_name) in enumerate(self._data[gid]):
                print(self._src_id, set_key, set_name, i)
                self.set_combobox.addItem(set_name, userData=set_key)
                print(self.set_combobox.currentIndex())
                if self._src_id == set_key:
                    set_idx = i

            print(set_idx)
            if set_idx > -1:
                self.set_combobox.setCurrentIndex(set_idx)

    def collect_parameter(self):
        xlog = self.xlog_checkBox.isChecked()
        ylog = self.ylog_checkBox.isChecked()

        mode = self.interp_comboBox.currentText().lower()

        if self.xaxis_comboBox.currentIndex() == 0:
            try:
                start = float(self.start_lineEdit.text())
                stop = float(self.stop_lineEdit.text())
                step = int(self.step_lineEdit.text())
            except ValueError:
                QtWidgets.QMessageBox.warning(self, 'Invalid axis', 'Values for axis are invalid or missing.')
                return False

            loggy = self.logspace_checkBox.isChecked()
            if loggy and ((start <= 0) or (stop <= 0)):
                QtWidgets.QMessageBox.warning(self, 'Invalid axis', 'Logarithmic axis cannot contain negative values.')
                return False

            x_src = (start, stop, step, loggy)
        else:
            self._src_id = self.set_combobox.currentData(QtCore.Qt.ItemDataRole.UserRole)
            x_src = (self._src_id,)

        self._dest_graph = self.dest_combobox.currentData(QtCore.Qt.ItemDataRole.UserRole)

        use_data = []
        for i in range(self.listWidget.count()):
            item = self.listWidget.item(i)
            if item.checkState() == QtCore.Qt.CheckState.Checked:
                use_data.append(item.data(QtCore.Qt.ItemDataRole.UserRole))

        self.new_data.emit(use_data, mode, xlog, ylog, x_src, self._dest_graph)

        return True

    def _save_state(self):
        self._src_id = self.set_combobox.currentData(QtCore.Qt.ItemDataRole.UserRole)
        self._dest_graph = self.dest_combobox.currentData(QtCore.Qt.ItemDataRole.UserRole)

    @QtCore.pyqtSlot(QtWidgets.QAbstractButton, name='on_buttonBox_clicked')
    def check_next_actions(self, bttn: QtWidgets.QAbstractButton):
        role = self.buttonBox.buttonRole(bttn)
        self._save_state()

        if role == self.buttonBox.ButtonRole.RejectRole:
            self.close()
        else:
            success = self.collect_parameter()

            if success and role == self.buttonBox.ButtonRole.AcceptRole:
                self.close()

