# -*- coding: utf-8 -*-

from qgis.core import QgsProject
from qgis.PyQt.QtCore import QSettings


class UserSetting(object):
    def __init__(self, name, type=str, default=None):
        self.name = name
        self.type = type
        self.default = default

    def __get__(self, instance, owner):
        return instance._qsettings.value(self.name, self.default, type=self.type)

    def __set__(self, instance, value):
        instance._qsettings.setValue(self.name, value)

    def __delete__(self, instance):
        instance._qsettings.remove(self.name)


class ProjectSetting(object):
    def __init__(self, name, type=[str, float, bool], default=None):
        self.name = name
        self.type = type
        self.default = default

    def __get__(self, instance, owner):
        if self.type == str:
            value, ok = QgsProject.instance().readEntry(
                instance.PROJECT_SCOPE, self.name
            )
        elif self.type == float:
            value, ok = QgsProject.instance().readDoubleEntry(
                instance.PROJECT_SCOPE, self.name
            )
        elif self.type == bool:
            value, ok = QgsProject.instance().readBoolEntry(
                instance.PROJECT_SCOPE, self.name
            )
        else:
            raise NotImplementedError(f"Type not supported: {self.type}")
        return value if ok else self.default

    def __set__(self, instance, value):
        if self.type == str:
            QgsProject.instance().writeEntry(instance.PROJECT_SCOPE, self.name, value)
        elif self.type == float:
            QgsProject.instance().writeEntryDouble(
                instance.PROJECT_SCOPE, self.name, value
            )
        elif self.type == bool:
            QgsProject.instance().writeEntryBool(
                instance.PROJECT_SCOPE, self.name, value
            )
        else:
            raise NotImplementedError(f"Type not supported: {self.type}")

    def __delete__(self, instance):
        QgsProject.instance().removeEntry(instance.PROJECT_SCOPE, self.name)


class Settings(object):
    GROUP = "PreCourlis"
    PROJECT_SCOPE = "PreCourlis"

    default_elevation = ProjectSetting("default_elevation", float, None)

    def __init__(self):
        self._qsettings = QSettings()
        self._qsettings.beginGroup(self.GROUP)


settings = Settings()
