# -*- coding:utf-8 -*-
""" Settings Module

Copied from Django Settings for LazyObject and LazySettings.
"""
import os
import importlib
from essen.exceptions import ImproperlyConfigured
from essen.utils.functional import LazyObject, empty
from . import default_settings

ENVIRONMENT_VARIABLE = "ESSEN_SETTINGS_MODULE"


class Settings(object):

    PREFIX = 'ESSEN_'
    TUPLE_SETTINGS = (
        'INCLUDE_PACKAGES',
    )

    def __init__(self, settings_module):
        mod = importlib.import_module(settings_module)

        # Load default settings.
        for setting in dir(default_settings):
            if not setting.isupper():
                continue

            setattr(self, setting, getattr(default_settings, setting))

        for setting in dir(mod):
            if not setting.isupper():
                continue

            value = getattr(mod, setting)

            if setting in self.TUPLE_SETTINGS and not isinstance(value, (list, tuple)):
                raise ValueError('List or tuple required for field %s.' % setting)

            setattr(self, setting, value)

    def __getattr__(self, item):
        """ Get value from env with specially named keys.
        """
        key = self.PREFIX + item
        return os.environ.get(key)

    def as_dict(self):
        _conf = dict()
        for setting in dir(self):
            if not setting.isupper():
                continue

            _conf[setting] = getattr(self, setting)

        return _conf


class UserSettingsHolder:
    """Holder for user configured settings."""
    # SETTINGS_MODULE doesn't make much sense in the manually configured
    # (standalone) case.
    SETTINGS_MODULE = None

    def __init__(self, default_settings):
        """
        Requests for configuration variables not in this class are satisfied
        from the module specified in default_settings (if possible).
        """
        self.__dict__['_deleted'] = set()
        self.default_settings = default_settings

    def __getattr__(self, name):
        if name in self._deleted:
            raise AttributeError
        return getattr(self.default_settings, name)

    def __setattr__(self, name, value):
        self._deleted.discard(name)
        super().__setattr__(name, value)

    def __delattr__(self, name):
        self._deleted.add(name)
        if hasattr(self, name):
            super().__delattr__(name)

    def __dir__(self):
        return sorted(
            s for s in [*self.__dict__, *dir(self.default_settings)]
            if s not in self._deleted
        )

    def is_overridden(self, setting):
        deleted = (setting in self._deleted)
        set_locally = (setting in self.__dict__)
        set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting)
        return deleted or set_locally or set_on_default

    def __repr__(self):
        return '<%(cls)s>' % {
            'cls': self.__class__.__name__,
        }


class LazySettings(LazyObject):
    """
    A lazy proxy for either global Essen settings or a custom settings object.
    The user can manually configure settings prior to using them. Otherwise,
    Essen uses the settings module pointed to by ESSEN_SETTINGS_MODULE.
    """
    def _setup(self, name=None):
        """
        Load the settings module pointed to by the environment variable. This
        is used the first time settings are needed, if the user hasn't
        configured settings manually.
        """
        settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
        if not settings_module:
            desc = ("setting %s" % name) if name else "settings"
            raise ImproperlyConfigured(
                "Requested %s, but settings are not configured. "
                "You must either define the environment variable %s "
                "or call settings.configure() before accessing settings."
                % (desc, ENVIRONMENT_VARIABLE))

        self._wrapped = Settings(settings_module)

    def __repr__(self):
        # Hardcode the class name as otherwise it yields 'Settings'.
        if self._wrapped is empty:
            return '<LazySettings [Unevaluated]>'
        return '<LazySettings "%(settings_module)s">' % {
            'settings_module': self._wrapped.SETTINGS_MODULE,
        }

    def __getattr__(self, name):
        """Return the value of a setting and cache it in self.__dict__."""
        if self._wrapped is empty:
            self._setup(name)
        val = getattr(self._wrapped, name)
        self.__dict__[name] = val
        return val

    def __setattr__(self, name, value):
        """
        Set the value of setting. Clear all cached values if _wrapped changes
        (@override_settings does this) or clear single values when set.
        """
        if name == '_wrapped':
            self.__dict__.clear()
        else:
            self.__dict__.pop(name, None)
        super().__setattr__(name, value)

    def __delattr__(self, name):
        """Delete a setting and clear it from cache if needed."""
        super().__delattr__(name)
        self.__dict__.pop(name, None)

    def configure(self, default_settings=default_settings, **options):
        """
        Called to manually configure the settings. The 'default_settings'
        parameter sets where to retrieve any unspecified values from (its
        argument must support attribute access (__getattr__)).
        """
        if self._wrapped is not empty:
            raise RuntimeError('Settings already configured.')

        holder = UserSettingsHolder(default_settings)
        for name, value in options.items():
            setattr(holder, name, value)
        self._wrapped = holder

    @property
    def configured(self):
        """Return True if the settings have already been configured."""
        return self._wrapped is not empty


settings = LazySettings()

# -*- coding:utf-8 -*-
""" Settings Module

Copied from Django Settings for LazyObject and LazySettings.
"""
import os
import importlib
from essen.exceptions import ImproperlyConfigured
from essen.utils.functional import LazyObject, empty
from . import default_settings

ENVIRONMENT_VARIABLE = "ESSEN_SETTINGS_MODULE"


class Settings(object):

    PREFIX = 'ESSEN_'
    TUPLE_SETTINGS = (
        'INCLUDE_PACKAGES',
    )

    def __init__(self, settings_module):
        mod = importlib.import_module(settings_module)

        # Load default settings.
        for setting in dir(default_settings):
            if not setting.isupper():
                continue

            setattr(self, setting, getattr(default_settings, setting))

        for setting in dir(mod):
            if not setting.isupper():
                continue

            value = getattr(mod, setting)

            if setting in self.TUPLE_SETTINGS and not isinstance(value, (list, tuple)):
                raise ValueError('List or tuple required for field %s.' % setting)

            setattr(self, setting, value)

    def __getattr__(self, item):
        """ Get value from env with specially named keys.
        """
        key = self.PREFIX + item
        return os.environ.get(key)

    def as_dict(self):
        _conf = dict()
        for setting in dir(self):
            if not setting.isupper():
                continue

            _conf[setting] = getattr(self, setting)

        return _conf


class UserSettingsHolder:
    """Holder for user configured settings."""
    # SETTINGS_MODULE doesn't make much sense in the manually configured
    # (standalone) case.
    SETTINGS_MODULE = None

    def __init__(self, default_settings):
        """
        Requests for configuration variables not in this class are satisfied
        from the module specified in default_settings (if possible).
        """
        self.__dict__['_deleted'] = set()
        self.default_settings = default_settings

    def __getattr__(self, name):
        if name in self._deleted:
            raise AttributeError
        return getattr(self.default_settings, name)

    def __setattr__(self, name, value):
        self._deleted.discard(name)
        super().__setattr__(name, value)

    def __delattr__(self, name):
        self._deleted.add(name)
        if hasattr(self, name):
            super().__delattr__(name)

    def __dir__(self):
        return sorted(
            s for s in [*self.__dict__, *dir(self.default_settings)]
            if s not in self._deleted
        )

    def is_overridden(self, setting):
        deleted = (setting in self._deleted)
        set_locally = (setting in self.__dict__)
        set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting)
        return deleted or set_locally or set_on_default

    def __repr__(self):
        return '<%(cls)s>' % {
            'cls': self.__class__.__name__,
        }


class LazySettings(LazyObject):
    """
    A lazy proxy for either global Essen settings or a custom settings object.
    The user can manually configure settings prior to using them. Otherwise,
    Essen uses the settings module pointed to by ESSEN_SETTINGS_MODULE.
    """
    def _setup(self, name=None):
        """
        Load the settings module pointed to by the environment variable. This
        is used the first time settings are needed, if the user hasn't
        configured settings manually.
        """
        settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
        if not settings_module:
            desc = ("setting %s" % name) if name else "settings"
            raise ImproperlyConfigured(
                "Requested %s, but settings are not configured. "
                "You must either define the environment variable %s "
                "or call settings.configure() before accessing settings."
                % (desc, ENVIRONMENT_VARIABLE))

        self._wrapped = Settings(settings_module)

    def __repr__(self):
        # Hardcode the class name as otherwise it yields 'Settings'.
        if self._wrapped is empty:
            return '<LazySettings [Unevaluated]>'
        return '<LazySettings "%(settings_module)s">' % {
            'settings_module': self._wrapped.SETTINGS_MODULE,
        }

    def __getattr__(self, name):
        """Return the value of a setting and cache it in self.__dict__."""
        if self._wrapped is empty:
            self._setup(name)
        val = getattr(self._wrapped, name)
        self.__dict__[name] = val
        return val

    def __setattr__(self, name, value):
        """
        Set the value of setting. Clear all cached values if _wrapped changes
        (@override_settings does this) or clear single values when set.
        """
        if name == '_wrapped':
            self.__dict__.clear()
        else:
            self.__dict__.pop(name, None)
        super().__setattr__(name, value)

    def __delattr__(self, name):
        """Delete a setting and clear it from cache if needed."""
        super().__delattr__(name)
        self.__dict__.pop(name, None)

    def configure(self, default_settings=default_settings, **options):
        """
        Called to manually configure the settings. The 'default_settings'
        parameter sets where to retrieve any unspecified values from (its
        argument must support attribute access (__getattr__)).
        """
        if self._wrapped is not empty:
            raise RuntimeError('Settings already configured.')

        holder = UserSettingsHolder(default_settings)
        for name, value in options.items():
            setattr(holder, name, value)
        self._wrapped = holder

    @property
    def configured(self):
        """Return True if the settings have already been configured."""
        return self._wrapped is not empty


settings = LazySettings()

# -*- coding:utf-8 -*- Settings Module  Copied from Django Settings for LazyObject and LazySettings. # Load default settings. Get value from env with specially named keys. Holder for user configured settings. # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. Requests for configuration variables not in this class are satisfied         from the module specified in default_settings (if possible). A lazy proxy for either global Essen settings or a custom settings object.     The user can manually configure settings prior to using them. Otherwise,     Essen uses the settings module pointed to by ESSEN_SETTINGS_MODULE. Load the settings module pointed to by the environment variable. This         is used the first time settings are needed, if the user hasn't         configured settings manually. # Hardcode the class name as otherwise it yields 'Settings'. Return the value of a setting and cache it in self.__dict__. Set the value of setting. Clear all cached values if _wrapped changes         (@override_settings does this) or clear single values when set. Delete a setting and clear it from cache if needed. Called to manually configure the settings. The 'default_settings'         parameter sets where to retrieve any unspecified values from (its         argument must support attribute access (__getattr__)). Return True if the settings have already been configured.