import simplejson
from django import template
from django.core.urlresolvers import reverse, NoReverseMatch

register = template.Library()

@register.tag
def breadcrumbs(parser, token):
    """
    Breadcrumbing tag
    {% breadcrumbs "['Home','Home','home']" "['Articles','Articles','articles']" "['object','object','object.get_absolute_url']" %}
    """
    bits = token.split_contents()
    if len(bits) < 2:
        raise template.TemplateSyntaxError, '%s takes exactly at least one argument' % bits[0]
    return Breadcrumbs(bits[1:])

class Breadcrumbs(template.Node):
    def __init__(self, bits):
        self.bits = bits


    def render(self, context):
        items = []

        for i, bit in enumerate(self.bits):
            bit = bit.replace('"', '')
            bit = bit.replace("'", '"')
            crumb = simplejson.loads(bit)

            item = dict(
                anchor = template.Template(crumb[0]).render(context),
                title = template.Template(crumb[1]).render(context),
            )

            try:
                args = crumb[3]
            except IndexError:
                args = None

            try:
                kwargs = crumb[4]
            except IndexError:
                kwargs = None

            try:
                # Try reversing the third argument in a crumb, or ...
                item['url'] = reverse(crumb[2], args = args, kwargs = kwargs)
            except NoReverseMatch:
                # ... try to resolve the variable's n urls
                item['anchor'] = template.Variable(crumb[0]).resolve(context)
                item['title'] = template.Variable(crumb[1]).resolve(context)
                item['url'] = template.Variable(crumb[2]).resolve(context)

            items.append(item)

        context['breadcrumbs'] = items

        return template.loader.get_template(
            'modules/breadcrumbs.html'
        ).render(context)