###
# Taken and adapted form django-google-analytics : http://
#
#
##
from django import template

from django.template import Context, loader
from django.conf import settings


register = template.Library()

def __clean_token(str_t, tag_name):
    if not (str_t[0] == str_t[-1] and str_t[0] in ('"', "'")):
        raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
    return str_t[1:-1]

def do_get_analytics(parser, token):
    code = None
    style = None
    tag_name = None
    try:
        # split_contents() knows not to split quoted strings.
        tokens = token.split_contents()
        if len(tokens) > 0 :
            tag_name = tokens[0]
        if len(tokens) > 1 :
            style = tokens[1]
        if len(tokens) > 2 :
            code = tokens[2]
    except ValueError:
        code = None
   
    if not code:
        code = getattr(settings,'GOOGLE_ANALYTICS_CODE',None)
    else:
        code = __clean_token(code, tag_name)

    if style:
        style = __clean_token(style, tag_name)
    else:
        style = 'async'

    return AnalyticsNode(code, style)
    
class AnalyticsNode(template.Node):
    def __init__(self, code=None, style='async'):
        self.code = code
        self.style = style
        
    def render(self, context):
        if not self.code:
            return ''
        
        if self.style == 'async':
            template_path = 'google_analytics/async_analytics_template.html'
        else:
            template_path = 'google_analytics/analytics_template.html'

        if self.code.strip() != '':
            t = loader.get_template(template_path)
            c = Context({
                'analytics_code': self.code,
            })
            return t.render(c)
        else:
            return ''
        
register.tag('analytics', do_get_analytics)
