from nmreval.io.tntreader import TNTReader

from ..Qt import QtCore, QtWidgets
from .._py.tntdialog import Ui_tntdialog


class QTNTReader(QtWidgets.QDialog, Ui_tntdialog):
    data_read = QtCore.pyqtSignal(dict)
    file_ext = ['.tnt']

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

        self.reader = TNTReader(fname)

        self.frame.hide()

        if fname is not None:
            if self.reader.onedimensional:
                self.export()
            else:
                self.set_gui()

    def __call__(self, fname, *args, **kwargs):
        self.reader(fname)
        for s in [self.widget, self.widget_2, self.widget_3]:
            s.__call__()

        self.frame.hide()
        self.frame_2.show()
        self.unknown_delay_combobox.clear()

        if self.reader.onedimensional:
            self.export()
        else:
            self.set_gui()

        return self

    def set_gui(self):
        self.label_3.setText(' x '.join(map(str, self.reader.shape)))
        for i, w in enumerate([self.widget, self.widget_2, self.widget_3], start=1):
            if self.reader.shape[i] == 1:
                w.hide()
            else:
                w.label.setText('Dimension {}'.format(i+1))
                w.dim = i
                w.add_items([x[0] for x in self.reader.delays.items() if len(x[1]) == self.reader.shape[i]])
                w.get_data.connect(self.show_delays)
                w.newDelay.connect(self.calc_delays)
        for x in self.reader.delays.items():
            if len(x[1]) in self.reader.shape[1:]:
                continue
            else:
                self.unknown_delay_combobox.addItem(x[0])
        if self.unknown_delay_combobox.count() == 0:
            self.frame_2.hide()

    @QtCore.pyqtSlot(str)
    def show_delays(self, label):
        vals = self.reader.delays[str(label)]
        self.sender().vals = '\n'.join(map(str, vals))

    def calc_delays(self):
        self.frame.show()
        self._caller = self.sender()

    @QtCore.pyqtSlot(name='on_pushButton_2_clicked')
    def cancel_delay(self):
        self.frame.hide()

    @QtCore.pyqtSlot(name='on_pushButton_clicked')
    def add_delay(self):
        try:
            s = float(self.start_lineedit.text())
        except ValueError:
            return
        try:
            e = float(self.end_lineedit.text())
        except ValueError:
            return
        d = []
        for w in [self.widget, self.widget_2, self.widget_3]:
            if w.isVisible():
                d.append(w.comboBox.currentText())
        self.reader.add_delay(s, e, self._caller.dim, self.lineEdit.text(),
                              staggered=self.checkBox_2.isChecked(), stag_steps=int(self.spinBox.value()),
                              log=self.checkBox.isChecked())
        self._caller.add_items(self.lineEdit.text())
        self.frame.hide()

    def export(self):
        d = []
        for w in [self.widget, self.widget_2, self.widget_3]:
            if w.isVisible():
                d.append(w.comboBox.currentText())
            else:
                d.append(None)

        ret_dic = self.reader.export(d)

        self.data_read.emit(ret_dic)
        self.close()

        return ret_dic

    def accept(self):
        self.export()
