# -*- coding: UTF-8 -*-

from django import template
from django.conf import settings
from django.views.decorators.cache import cache_page

register = template.Library()

@register.tag(name="get_delicious_links")
def do_delicious_links(parser, token):
    """
    {% get_delicious_lings as links%}

    Get the last del.icio.us entries for the configured user in
    DELICIOUS_USER settings.

    Caches the result for 6 hours.
    Delicious tags is based on http://www.djangosnippets.org/snippets/819/
    """
    bits = token.contents.split()
    if len(bits) == 3 and bits[1] == 'as':
        return DeliciousObject(bits[2])
    else:
        return template.TemplateSyntaxError, "Invalid sytax: use get_delicious_links as variable_name"
do_delicious_links = cache_page(do_delicious_links, 21600)

class DeliciousObject(template.Node):
    def __init__(self, context_variable):
        self.context_variable = context_variable

    def render(self, context):
        try:
            import feedparser
            d = feedparser.parse('http://del.icio.us/rss/%s'% settings.DELICIOUS_USER)
            delicious=[]
            for entry in d['entries'][:min(8,len(d['entries']))]:
                title=str(entry['title'].encode('ascii', 'xmlcharrefreplace'))
                delicious.append({'title':title,'link':str(entry['links'][0]['href'])})
        except:
            delicious=[]
        context[self.context_variable] = delicious
        return ""