from django.template import Library, Node
from django.template.defaulttags import TemplateIfParser
from django.template.base import TemplateSyntaxError, VariableDoesNotExist

register = Library()


def parse_classes(parser, content):
    classes_and_conditions = []
    classes_splitted = content.split(",")
    for class_value in classes_splitted:
        class_parts = class_value.split(":")
        if len(class_parts) != 2:
            raise TemplateSyntaxError("class must contain a name and condition")
        classes_and_conditions.append({
            'name': class_parts[0].replace("'", "").replace('"', "").strip(),
            'condition': TemplateIfParser(parser, class_parts[1].strip().split(" ")).parse()
        })
    return classes_and_conditions


class Classes(Node):
    classes = None

    def __init__(self, classes):
        self.classes = classes

    def render(self, context):
        classes_to_show = []
        for class_parts in self.classes:
            try:
                if class_parts['condition'].eval(context):
                    classes_to_show.append(class_parts['name'])
            except VariableDoesNotExist:
                pass
        return " ".join(classes_to_show)


def classes(parser, token):
    bits = token.split_contents()
    if len(bits[1:]) < 1:
        raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0])

    offset = len(bits[0]) + 1
    return Classes(parse_classes(parser, token.contents[offset:]))


register.tag(classes)