from string import Template as StringTemplate
from unittest.mock import patch

import sass
from compressor.css import CssCompressor
from django.http import HttpResponse
from django.template import Context, Template
from django.utils.html import strip_tags
from django.views.decorators.cache import cache_page
from django_libsass import get_include_paths

from ocyan.core.plugins import get_sass_functions

from .definitions import get_theme

OXYAN_CSS_INCLUDE = StringTemplate(
    """{% load compress static %}{% compress css inline $theme_name %}<link rel="stylesheet" id="sass_$theme_name" type="text/x-scss" media="print" href="{% static 'scss/base.scss' %}">{% endcompress %}"""
)


@cache_page(60 * 15)
def preview_theme_css(request, theme_name):
    context = get_theme(theme_name)
    with patch("ocyan.plugin.themes.sassfunctions.definitions", context):
        tpl = Template(OXYAN_CSS_INCLUDE.substitute(theme_name=theme_name))
        css = tpl.render(Context())

    return HttpResponse(strip_tags(css), content_type="text/css")


@cache_page(60 * 15)
def preview_theme_css2(request, theme_name):
    context = get_theme(theme_name)
    with patch("ocyan.plugin.themes.sassfunctions.definitions", context):
        # pylint: disable=no-value-for-parameter
        a = CssCompressor()
        path = a.get_filename("scss/base.scss")
        css = sass.compile(
            filename=path,
            output_style="nested",
            source_comments=True,
            include_paths=get_include_paths(),
            custom_functions=get_sass_functions(),
        )

    return HttpResponse(css, content_type="text/css")
