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

CSP_SELF = ["'self'"]


class SecurityConfig(plugins.OcyanPluginConfig):
    def contribute_to_middleware(self, middleware):
        return middleware + ["csp.middleware.CSPMiddleware"]

    def contribute_to_csp_settings(self, csp_settings):
        excluded_url_prefixes = [
            "/admin/",
            "/manage/",
        ]

        if config.i18n_enabled:
            for code in config.get("i18n", "languages"):
                excluded_url_prefixes.append("/%s/admin/" % code)
                excluded_url_prefixes.append("/%s/manage/" % code)

        return csp_settings + CSPSetting(
            default_src=CSP_SELF,
            style_src=CSP_SELF + ["'unsafe-inline'", "fonts.googleapis.com"],
            script_src=CSP_SELF,
            connect_src=CSP_SELF,
            img_src=CSP_SELF + ["data:"],
            font_src=CSP_SELF,
            object_src=[
                "'none'"
            ],  # wapiti says it should be like this, but that means no embedded pdf's!
            child_src=CSP_SELF + ["www.youtube.com"],
            excluded_url_prefixes=excluded_url_prefixes,
            form_action=CSP_SELF,
            frame_ancestors=CSP_SELF,
            base_uri=CSP_SELF,
        )

    def contribute_to_settings(self, settings):
        csp_settings = plugins.get_csp_settings()

        CSP_SETTINGS = {
            "CSP_DEFAULT_SRC": csp_settings.default_src,
            "CSP_STYLE_SRC": csp_settings.style_src,
            "CSP_SCRIPT_SRC": csp_settings.script_src,
            "CSP_CONNECT_SRC": csp_settings.connect_src,
            "CSP_IMG_SRC": csp_settings.img_src,
            "CSP_FONT_SRC": csp_settings.font_src,
            "CSP_OBJECT_SRC": csp_settings.object_src,
            "CSP_CHILD_SRC": csp_settings.child_src,
            "CSP_EXCLUDE_URL_PREFIXES": csp_settings.excluded_url_prefixes,
            "CSP_FORM_ACTION": csp_settings.form_action,
            "CSP_FRAME_ANCESTORS": csp_settings.frame_ancestors,
            "CSP_INCLUDE_NONCE_IN": ["script-src"],
            "CSP_BASE_URI": csp_settings.base_uri,
            "SECURE_HSTS_SECONDS": 63072000,
            "SECURE_HSTS_INCLUDE_SUBDOMAINS": True,
            "SECURE_HSTS_PRELOAD": True,
        }

        return merge_dicts(settings, CSP_SETTINGS)

    def contribute_to_installed_apps(self, installed_apps):
        installed_apps.django.register_extension(
            "ocyan.plugin.security.security_main_extension", "ocyan.main"
        )
        return installed_apps
