from ..Qt import QtWidgets, QtCore, QtGui
from .._py.save_fit_parameter import Ui_fitparameter_save_dialog


class QSaveFit(QtWidgets.QDialog, Ui_fitparameter_save_dialog):
    def __init__(self, path: str = None, parent=None):
        super().__init__(parent=parent)

        self.pnames = None
        self.outpath = path

        self.setupUi(self)

        self.tableWidget.cellDoubleClicked.connect(self.clicketyclick)
        self.tableWidget.setColumnCount(2)

        self.save_path_line.textEdited.connect(lambda: self.change_path(self.save_path_line.text()))
        self.save_path_button.clicked.connect(self.set_save_path)

        self.header_edit.hide()
        self.header_checkBox.stateChanged.connect(lambda state: self.header_edit.setVisible(state))

        self.missing_value_line.setValidator(QtGui.QDoubleValidator())

    def set_parameter(self, fits: dict):
        for model_name, parameter in fits.items():
            for p in parameter:
                item = QtWidgets.QTableWidgetItem(p)
                item2 = QtWidgets.QTableWidgetItem(model_name)
                item2.setToolTip(model_name)
                row = self.tableWidget.rowCount()
                self.tableWidget.setRowCount(row+1)
                self.tableWidget.setItem(row, 0, item)
                self.tableWidget.setItem(row, 1, item2)

        self.tableWidget.resizeColumnsToContents()

    @QtCore.pyqtSlot(int, int)
    def clicketyclick(self, row: int, _):
        if self.col_line.text():
            self.col_line.setText(self.col_line.text() + '; ' + self.tableWidget.item(row, 0).text())
        else:
            self.col_line.setText(self.tableWidget.item(row, 0).text())

    def set_save_path(self):
        fname, _ = QtWidgets.QFileDialog.getSaveFileName(options=QtWidgets.QFileDialog.DontConfirmOverwrite,
                                                         directory=self.outpath)

        if fname:
            self.outpath = fname
            self.save_path_line.setText(fname)

    def add_header(self, idx: int):
        self.textEdit.setVisible(idx != 0)

    @QtCore.pyqtSlot(name='on_usage_button_clicked')
    def show_usage(self):
        _ = QtWidgets.QMessageBox.information(self, 'Usage',
                                              'Separate each column by semicolon.\n'
                                              'Use p_err to save error of parameter p.\n'
                                              'If a column shall contain different parameters use {p1/p2}.\n'
                                              'KWW mean is calculated by mean(τ,β), KWW peak by peak(τ,β).')

    def accept(self):
        super().accept()
