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

from configtype.jsonconfig import JsonFinder
from django.utils.functional import cached_property

logger = logging.getLogger(__name__)


def _get_jsonfinder():
    for finder in sys.meta_path:
        if isinstance(finder, JsonFinder):
            return finder
    return None


def _load_config_values():
    config_module_name = f"{__package__}.json"
    try:
        config_module = importlib.import_module(config_module_name)
    except ImportError:
        if _get_jsonfinder() is None:
            logger.debug(
                "No configtype search paths configured for %s; using empty defaults",
                config_module_name,
            )
        else:
            logger.debug(
                "No JSON config found for %s via configured search paths; using empty defaults",
                config_module_name,
            )
        return {}

    values = {}
    for key in dir(config_module):
        if key.startswith("__"):
            continue
        values[key] = copy.deepcopy(getattr(config_module, key))
    return values


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()
