from django import template
from django.core.urlresolvers import reverse
from django.template import resolve_variable

register = template.Library()

@register.tag()
def link_to(parser, token):
    """ Generates a link to a model instance

    Attempts to determine a link to the supplied model instance by first looking
    for a "get_absolute_url" method. It then looks for a named url with the
    pattern "appname-modelname". Finally it returns a relative url to
    "/appname/modelname/instancepk/".

    Usage: {% link_to instance "Anchor text" %}

    """
    try:
        tag_name, instance, anchor_text = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("\"link_to\" tag requires two arguments.")
    return LinkToNode(instance, anchor_text)

class LinkToNode(template.Node):
    def __init__(self, instance, anchor_text):
        self.instance_name = instance
        self.anchor_text = anchor_text.strip("\"\'")
    def render(self, context):
        try:
            anchor_text = resolve_variable(self.anchor_text, context)
        except template.VariableDoesNotExist:
            anchor_text = self.anchor_text
        tpl = '<a href="%s">%s</a>'
        instance = resolve_variable(self.instance_name, context)
        if getattr(instance, "get_absolute_url", None):
            return tpl % (instance.get_absolute_url(), anchor_text)
        try:
            url = reverse("%s-%s" % (instance._meta.app_label,
                                     instance._meta.verbose_name),
                          args=[instance._get_pk_val()])
            return tpl % (url, anchor_text)
        except NoReverseMatch:
            url = "/%s/%s/%s/" % (instance._meta.app_label,
                                  instance._meta.verbose_name,
                                  instance._get_pk_val())
            return tpl % (url, anchor_text)