import threading
from importlib import import_module

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


@configfile
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


config = FenderConfig()
