from django.conf import settings
from django.template.backends.base import BaseEngine
from django.template.backends.django import DjangoTemplates
from django.template.engine import Engine


class OcyanEngine(Engine):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if (
            not self.debug
            and self.loaders[0][0] != "django.template.loaders.cached.Loader"
        ):
            self.loaders = [("django.template.loaders.cached.Loader", self.loaders)]


class OcyanDjangoTemplates(DjangoTemplates):
    def __init__(self, params):  # pylint: disable=W0231
        # Copied over from parent class
        params = params.copy()
        options = params.pop("OPTIONS").copy()
        options.setdefault("autoescape", True)
        options.setdefault("debug", settings.DEBUG)
        options.setdefault(
            "file_charset", getattr(settings, "FILE_CHARSET", settings.DEFAULT_CHARSET)
        )
        libraries = options.get("libraries", {})
        options["libraries"] = self.get_templatetag_libraries(libraries)
        # calls parent's super class
        BaseEngine.__init__(self, params)  # pylint: disable=W0233
        # Use our engine
        self.engine = OcyanEngine(self.dirs, self.app_dirs, **options)
