from nmreval.io.bds_reader import BDSReader
from ..Qt import QtCore, QtWidgets
from .._py.bdsdialog import Ui_Dialog


class QBDSReader(QtWidgets.QDialog, Ui_Dialog):
    data_read = QtCore.pyqtSignal(list)
    file_ext = ['.eps']

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

        if self.fname is not None:
            self.reader = BDSReader(fname)
            self.setup_gui()

    def __call__(self, fname: str):
        self.reader = BDSReader(fname)
        self.fname = fname
        self.setup_gui()

        return self

    def setup_gui(self):
        self.listWidget.clear()
        self.label.setText(f'Found entries for {self.reader.fname.name}')

        self.make_list(True)

    @QtCore.pyqtSlot(QtWidgets.QAbstractButton, name='on_buttonGroup_buttonClicked')
    def change_list(self, bttn: QtWidgets.QAbstractButton):
        self.make_list(bttn == self.freq_button)

    def make_list(self, use_freq: bool) -> None:
        self.listWidget.clear()
        if use_freq:
            secondary = self.reader.set_temp
        else:
            secondary = self.reader.frequencies

        for x2 in secondary:
            item = QtWidgets.QListWidgetItem(f'{x2:.8g}')
            item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsSelectable)
            item.setCheckState(QtCore.Qt.Checked)
            self.listWidget.addItem(item)

    def accept(self):
        data = []

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

        xmode = 'freq' if self.freq_button.isChecked() else 'temp'

        for (mode, cb) in [
            ('epsilon', self.eps_checkBox),
            ('sigma', self.cond_checkBox),
            ('modulus', self.modul_checkBox),
            ('capacity', self.cap_checkBox),
            ('time', self.time_checkBox),
            ('sample_temp', self.temp_checkBox),
            ('loss_factor', self.loss_checkBox)
        ]:
            if cb.checkState() == QtCore.Qt.Checked:
                values = self.reader.export(ymode=mode, xmode=xmode)
                for t in x2:
                    data.append(values[t])

        self.data_read.emit(data)

        super().accept()
