from copy import deepcopy

from django.conf import settings
from django.utils.module_loading import import_string

from ocyan.core.fender import config

from oxyan.themes.definitions.default import variables as default_theme


def get_theme(name, mixins=()):
    _theme = deepcopy(default_theme)
    # read variables from the configured theme and prefer them over the default values
    configured_theme = import_string("oxyan.themes.definitions.%s.variables" % name)
    _theme.update(configured_theme)

    for _theme_name in mixins:
        _theme.update(
            import_string("oxyan.themes.definitions.%s.variables" % _theme_name)
        )

    # read variables from the project config and prefer them over the configured theme
    project_theme = config.get_section("themes") or {}
    _theme.update(project_theme)

    # Fallbacks for old theme color names
    _theme["primary_color"] = _theme["primary"]
    _theme["secondary_color"] = _theme["secondary"]
    _theme["info_color"] = _theme["info"]
    _theme["success_color"] = _theme["success"]
    _theme["danger_color"] = _theme["danger"]
    _theme["warning_color"] = _theme["warning"]
    return _theme


theme_name = settings.OXYAN_THEME
mixin_themes = settings.OXYAN_THEME_MIXINS

theme = get_theme(theme_name, mixin_themes)


def get_lazy_definitions():
    definitions_string = getattr(settings, "OXYAN_LAZY_THEME_DEFINITIONS", None)

    if definitions_string is None:
        return {}

    return import_string(definitions_string)()


def get(name, fallback=None):
    # update theme with lazy definitions
    theme.update(get_lazy_definitions())
    return theme.get(name, fallback)
