from nmreval.math import apodization
from nmreval.lib.importer import find_models
from nmreval.utils.text import convert

from ...Qt import QtCore, QtWidgets, QtGui
from ...lib.forms import FormWidget
from ..._py.editsignalwidget import Ui_Form


class EditSignalWidget(QtWidgets.QWidget, Ui_Form):
    do_something = QtCore.pyqtSignal(str, tuple)
    get_values = QtCore.pyqtSignal()
    preview_triggered = QtCore.pyqtSignal(str)

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

        self.apodlist = find_models(apodization)

        self.ls_lineEdit.hide()
        self.ls_lineEdit.setValidator(QtGui.QDoubleValidator())

        for ap in self.apodlist:
            self.apodcombobox.addItem(str(ap().name))
            self.change_apodization(0)

        self.baselinebutton.clicked.connect(lambda: self.apply_changes('bl'))
        self.zfbutton.clicked.connect(lambda: self.apply_changes('zf'))
        self.phasebutton.clicked.connect(lambda: self.apply_changes('ph'))
        self.apodbutton.clicked.connect(lambda: self.apply_changes('ap'))
        self.leftshiftbutton.clicked.connect(lambda: self.apply_changes('ls'))
        self.fourierutton.clicked.connect(lambda: self.apply_changes('ft'))

        self.apod_prev_button.clicked.connect(lambda: self.preview_triggered.emit('ap'))
        self.phase_prev_button.clicked.connect(lambda: self.preview_triggered.emit('ph'))

    @QtCore.pyqtSlot(str)
    def apply_changes(self, sender):
        if sender in ['bl', 'zf', 'ft']:
            self.do_something.emit(sender, tuple())

        elif sender == 'ls':
            if self.leftshift_comboBox.currentIndex() == 0:
                _nop = int(self.ls_spinBox.text())
                stype = 'pts'
            else:
                try:
                    _nop = float(self.lineEdit.text())
                except ValueError:
                    _nop = 0.0
                stype = 'time'
            self.do_something.emit(sender, (_nop, stype))

        elif sender == 'ap':
            apodmodel = self.apodlist[self.apodcombobox.currentIndex()]
            p = [float(x.text()) for x in self.apod_box.findChildren(QtWidgets.QLineEdit)]
            self.do_something.emit(sender, (p, apodmodel))

        elif sender == 'ph':
            pvt = float(self.pivot_lineedit.text())
            if self.autophase_check.isChecked():
                self.do_something.emit('autoph', (pvt,))
            else:
                ph0 = float(self.ph0slider.value())
                ph1 = float(self.ph1slider.value())
                self.do_something.emit(sender, (ph0, ph1, pvt))

        else:
            print('You should never reach this by accident.')

    @QtCore.pyqtSlot(int, name='on_apodcombobox_currentIndexChanged')
    def change_apodization(self, index):
        apod_func = self.apodlist[index]
        self.apod_name_label.setText(convert(apod_func.equation))

        while self.apod_layout.count():
            item = self.apod_layout.takeAt(0)
            try:
                item.widget().deleteLater()
            except AttributeError:
                pass

        for k, v in enumerate(apod_func.params):
            widgt = FormWidget(name=v)
            self.apod_layout.addWidget(widgt)

    @QtCore.pyqtSlot(int, name='on_leftshift_comboBox_currentIndexChanged')
    def change_ls(self, idx):
        if idx:
            self.ls_lineEdit.show()
            self.ls_spinBox.hide()
        else:
            self.ls_lineEdit.hide()
            self.ls_spinBox.show()
