from django import template
from django.template.defaultfilters import slugify
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.core.cache import cache

from .. import models, app_settings

register = template.Library()

@register.tag
def editablecontent(parser, token):
    args = token.split_contents()[1:]
    if len(args) < 1:
        raise template.TemplateSyntaxError("'editablecontent' tag needs at least one argument.")
    nodelist = parser.parse(('endeditablecontent',))
    parser.delete_first_token()
    return EditableContentNode([parser.compile_filter(arg) for arg in args], nodelist)

class EditableContentNode(template.Node):
    def __init__(self, indexes, nodelist):
        self.indexes = indexes
        self.nodelist = nodelist

    def render(self, context):
        values = [ slugify(index.resolve(context)) for index in self.indexes ]
        name = '_' + '_'.join(values)
        kwargs = { 'name': escape(name), 'more_class': '' }
        templ= u'<div class="aloha-editable {name} {more_class}" data-name="{name}">{content}</div>'
        try:
            content = cache.get(app_settings.cache_key(name))
            if content is None:
                content = models.ContentBlock.objects.get(name=name).content
                cache.set(app_settings.cache_key(name), content,
                        app_settings.EDITOR_CACHE_TIMEOUT)
            elif content is False:
                content = self.nodelist.render(context)
        except models.ContentBlock.DoesNotExist:
            content = self.nodelist.render(context)
            cache.set(app_settings.cache_key(name), False,
                    app_settings.EDITOR_CACHE_TIMEOUT)
        if content.strip() == '':
            kwargs['more_class'] = 'empty'
        kwargs['content'] = content
        return mark_safe(templ.format(**kwargs))
