# -*- coding: utf-8 -*-
from ocyan.core.plugins import OcyanPluginConfig
from ocyan.core.utils import find_first, merge_dicts, CSPSetting
from ocyan.core.fender import config

from . import constants

COOKIE_JAR_TEMPLATE_SETTINGS = {
    "OPTIONS": {
        "context_processors": ["ocyan.plugin.cookie_jar.contextprocessors.cookie_jar"]
    }
}


class CookieJarConfig(OcyanPluginConfig):
    def contribute_to_installed_apps(self, installed_apps):
        installed_apps.ocyan.append("ocyan.plugin.cookie_jar")
        installed_apps.oscar.register_extension(
            "ocyan.plugin.cookie_jar.cookiejar_basket_extension",
            "ocyan.plugin.oscar_basket.basket",
        )
        return installed_apps

    def contribute_to_settings(self, settings):
        # find django template settings dict
        django_templates = find_first(
            lambda x: x["BACKEND"].endswith("DjangoTemplates"), settings["TEMPLATES"]
        )

        # configure templates
        merge_dicts(django_templates, COOKIE_JAR_TEMPLATE_SETTINGS, overwrite=True)
        return merge_dicts(
            settings,
            {
                "COOKIE_JAR_SCRIPT_DELAY": constants.COOKIE_JAR_SCRIPT_DELAY,
                "COOKIE_JAR_ENABLED": True,
            },
        )

    def contribute_to_i18n_fields(self, fields_dict):
        fields_dict.update({"cookie_jar.cookiesettings.cookie_message": True})
        return fields_dict

    def contribute_to_csp_settings(self, csp_settings):
        cookie_jar_settings = config.get_section("cookie_jar")
        if cookie_jar_settings and (
            "google_tag_manager" in cookie_jar_settings
            or "google_analytics" in cookie_jar_settings
        ):
            return csp_settings + CSPSetting(
                script_src=["www.googletagmanager.com", "www.google-analytics.com"],
                connect_src=["www.google-analytics.com"],
                img_src=["www.google-analytics.com"],
            )

        return csp_settings


class OcyanCookieJarConfig(CookieJarConfig):
    def contribute_to_installed_apps(self, installed_apps):
        installed_apps = super().contribute_to_installed_apps(installed_apps)
        installed_apps.ocyan.append("ocyan.plugin.cookie_jar.ocyan_cookiejar")
        return installed_apps


class OxyanCookieJarConfig(CookieJarConfig):
    def contribute_to_installed_apps(self, installed_apps):
        installed_apps = super().contribute_to_installed_apps(installed_apps)
        installed_apps.front.register_extension(
            "ocyan.plugin.cookie_jar", "oxyan.themes"
        )
        installed_apps.front.register_extension(
            "ocyan.plugin.cookie_jar", "ocyan.plugin.barebone"
        )
        return installed_apps
