from pathlib import Path
import PreCourlis

from qgis.PyQt import QtWidgets, uic

from PreCourlis.core.settings import settings

FORM_CLASS, _ = uic.loadUiType(
    Path(PreCourlis.__file__).parent.resolve() / "ui" / "settings_dialog.ui"
)


class SettingsDialog(QtWidgets.QDialog, FORM_CLASS):

    CLEAR_VALUE = -99999999.0

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

    def accept(self, *args, **kwargs):
        self.saveSettings()
        super().accept(*args, **kwargs)

    def init_default_elevation_spin_box(self):
        self.defaultElevationQgsDoubleSpinBox.setMinimum(self.CLEAR_VALUE)
        self.defaultElevationQgsDoubleSpinBox.setClearValue(
            self.CLEAR_VALUE, self.tr("Not set")
        )
        self.loadSetting()

    def defaultElevation(self):
        if self.defaultElevationQgsDoubleSpinBox.value() == self.CLEAR_VALUE:
            return None
        else:
            return self.defaultElevationQgsDoubleSpinBox.value()

    def setDefaultElevation(self, value):
        if value is None:
            self.defaultElevationQgsDoubleSpinBox.setValue(self.CLEAR_VALUE)
        else:
            self.defaultElevationQgsDoubleSpinBox.setValue(value)

    def loadSetting(self):
        self.setDefaultElevation(settings.default_elevation)

    def saveSettings(self):
        if self.defaultElevation() is None:
            del settings.default_elevation
        else:
            settings.default_elevation = self.defaultElevation()
