import copy
import importlib
import logging
import threading
from importlib import import_module

from django.utils.functional import cached_property

logger = logging.getLogger(__name__)


def _load_config_values():
    """Load optional ``ocyan.core.json`` values without requiring host setup.

    Configtype registers the JSON finder during host configuration.  Core is also
    imported by package metadata and plugin discovery before that configuration
    exists, so the absence of the optional JSON module must retain the defaults.
    Errors raised while reading a discovered configuration remain visible.
    """
    config_module_name = "%s.json" % __package__
    try:
        config_module = importlib.import_module(config_module_name)
    except ModuleNotFoundError as error:
        if error.name != config_module_name:
            raise
        logger.debug("No optional core JSON configuration is available yet")
        return {}

    return {
        name: copy.deepcopy(getattr(config_module, name))
        for name in dir(config_module)
        if not name.startswith("__")
    }


class FenderConfig(threading.local):
    """
    Interface for accessing the fender settings from the json config
    """

    settings = {}
    ocyan_plugins = []

    def sections(self):
        return self.settings.keys()

    def has_section(self, name):
        return name in self.settings

    def has_option(self, section, option):
        return self.has_section(section) and option in self.settings[section]

    def get_section(self, section):
        return self.settings.get(section, None)

    def get(self, section, option, fallback=None):
        if self.has_option(section, option):
            return self.settings[section][option]

        return fallback

    @cached_property
    def is_webshop(self):
        # if it doesn't have the barebone plugin, it is a webshop
        # pylint: disable=no-member
        return not any(["barebone" in x for x in self.ocyan_plugins])

    @cached_property
    def i18n_enabled(self):
        try:
            import_module("ocyan.i18n")
        except ImportError:
            return False

        return "i18n" in self.settings


for key, value in _load_config_values().items():
    setattr(FenderConfig, key, value)


config = FenderConfig()
