from collections import namedtuple

from django import template

from ocyan.plugin.unusedcss.models import TemplateInlineCSS

register = template.Library()

CSSDefinition = namedtuple("CSSDefinition", ["is_active", "css"])


@register.simple_tag(takes_context=True)
def unusedcss(context, template_name):
    if "unusedcss_lazy" in context:
        return CSSDefinition(False, "")

    request = context.get("request")
    if request is None:
        return CSSDefinition(False, "")

    if "unusedcss" in request.GET:
        return CSSDefinition(False, "")
    else:
        user = getattr(request, "user", None)
        if user is not None and user.username == "unusedcss":
            return CSSDefinition(False, "")

    try:
        css = TemplateInlineCSS.objects.get(name=template_name)
        return CSSDefinition(True, css.inline_css)
    except TemplateInlineCSS.DoesNotExist:
        return CSSDefinition(False, "")
