import os

from nmreval.configs import *
from nmreval.io.graceeditor import GraceEditor

from ..Qt import QtWidgets, QtGui
from .._py.agroptiondialog import Ui_Dialog


class QGraceSettings(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self.setupUi(self)
        self._default_path = config_paths().joinpath('Default.agr')
        self._default = GraceEditor(self._default_path)

        self.setup_ui()

    def setup_ui(self):
        page = self._default.size
        self.widthDoubleSpinBox.setValue(page[0])
        self.heightDoubleSpinBox.setValue(page[1])

        view = self._default.get_property(0, 'view')
        self.leftMarginDoubleSpinBox.setValue(self._default.convert(view[0], direction='abs'))
        self.bottomMarginDoubleSpinBox.setValue(self._default.convert(view[1], direction='abs'))
        self.rightMarginDoubleSpinBox.setValue(page[0]-self._default.convert(view[2], direction='abs'))
        self.topMarginDoubleSpinBox.setValue(page[1]-self._default.convert(view[3], direction='abs'))


class GraceMsgBox(QtWidgets.QDialog):
    def __init__(self, fname, parent=None):
        super(GraceMsgBox, self).__init__(parent=parent)

        agr = GraceEditor()
        agr.parse(fname)

        layout = QtWidgets.QGridLayout()
        self.setLayout(layout)

        label = QtWidgets.QLabel('%s already exists. Select one of the options or cancel:' % os.path.split(fname)[1])
        layout.addWidget(label, 1, 1, 1, 2)

        self.button_grp = QtWidgets.QButtonGroup(self)

        self.overwrite_radiobutton = QtWidgets.QRadioButton('Overwrite file', parent=self)
        self.overwrite_radiobutton.setChecked(True)
        self.button_grp.addButton(self.overwrite_radiobutton, id=0)
        layout.addWidget(self.overwrite_radiobutton, 2, 1, 1, 2)

        self.new_graph_button = QtWidgets.QRadioButton('Create new graph', parent=self)
        self.button_grp.addButton(self.new_graph_button, id=1)
        layout.addWidget(self.new_graph_button, 3, 1, 1, 2)

        self.addgraph_button = QtWidgets.QRadioButton('Add sets to graph', parent=self)
        self.button_grp.addButton(self.addgraph_button, id=3)
        layout.addWidget(self.addgraph_button, 4, 1, 1, 1)

        self.graph_combobox = QtWidgets.QComboBox(self)
        self.graph_combobox.addItems(['G' + str(g.idx) for g in agr.graphs])
        layout.addWidget(self.graph_combobox, 4, 2, 1, 1)

        self.buttonbox = QtWidgets.QDialogButtonBox(self)
        self.buttonbox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok)
        layout.addWidget(self.buttonbox, 5, 1, 1, 2)

        self.buttonbox.rejected.connect(self.reject)
        self.buttonbox.accepted.connect(self.accept)

    def accept(self) -> None:
        super().accept()
        self.setResult(self.button_grp.checkedId())
        if self.button_grp.checkedId() == 3:
            self.setResult(int(self.graph_combobox.currentText()[1:]) + 2)

    def reject(self) -> None:
        super().reject()
        self.setResult(-1)


class GeneralConfiguration(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        layout = QtWidgets.QVBoxLayout()
        layout.setContentsMargins(3, 3, 3, 3)

        intro = QtWidgets.QLabel('Changes become active after restart.')
        layout.addWidget(intro)

        parser = read_configuration()
        for sec in parser.sections():
            group = QtWidgets.QGroupBox(sec, self)

            layout2 = QtWidgets.QGridLayout()
            layout2.setContentsMargins(3, 3, 3, 3)
            row = 0
            for key, value in parser.items(sec):
                label = QtWidgets.QLabel(key.capitalize(), self)
                layout2.addWidget(label, row, 0)
                if (sec, key) in ALLOWED_VALUE:
                    edit = QtWidgets.QComboBox(self)
                    edit.addItems(ALLOWED_VALUE[(sec, key)])
                    edit.setCurrentIndex(edit.findText(value))
                else:
                    edit = QtWidgets.QLineEdit(self)
                    edit.setText(value)
                    try:
                        _ = float(value)
                        edit.setValidator(QtGui.QDoubleValidator())
                    except ValueError:
                        pass

                layout2.addWidget(edit, row, 1)
                row += 1

            group.setLayout(layout2)

            layout.addWidget(group)

        self.buttonbox = QtWidgets.QDialogButtonBox(self)
        self.buttonbox.setStandardButtons(self.buttonbox.Ok|self.buttonbox.Cancel)
        self.buttonbox.rejected.connect(self.close)
        self.buttonbox.accepted.connect(self.accept)
        layout.addWidget(self.buttonbox)

        self.setLayout(layout)

    def accept(self):
        options = {}
        for section in self.findChildren(QtWidgets.QGroupBox):
            args = {}

            layout = section.layout()
            for row in range(layout.rowCount()):
                key = layout.itemAtPosition(row, 0).widget().text()

                value_widget = layout.itemAtPosition(row, 1).widget()
                if isinstance(value_widget, QtWidgets.QComboBox):
                    value = value_widget.currentText()
                elif isinstance(value_widget, QtWidgets.QLineEdit):
                    value = value_widget.text()
                elif isinstance(value_widget, QtWidgets.QDoubleSpinBox):
                    value = value_widget.text()
                else:
                    raise TypeError('Config key %s has unknown type %s' % (key, repr(value_widget)))

                args[key] = value

            options[section.title()] = args

        write_configuration(options)

        super().accept()
