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 = {}

    @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 = {}
        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 gid == current_gid:
                self.make_list(sets)
            self._data[gid] = sets
        self.graph_combobox.blockSignals(False)
        self.change_graph(0)

    def make_list(self, current_sets):
        for sid, set_name in current_sets:
            item = QtWidgets.QListWidgetItem(set_name)
            item.setData(QtCore.Qt.UserRole, sid)
            item.setCheckState(QtCore.Qt.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.UserRole)
        if gid is not None:
            for set_key, set_name in self._data[gid]:
                self.set_combobox.addItem(set_name, userData=set_key)

    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:
            x_src = (self.set_combobox.currentData(QtCore.Qt.UserRole),)

        dest_graph = self.dest_combobox.currentData(QtCore.Qt.UserRole)

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

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

        return True

    def accept(self):
        success = self.collect_parameter()
        if success:
            super().accept()
