"""
Django template tags to enable the use of the modconcat Apache module. Set ENABLE_CONCAT=True in settings.py to enable.

http://code.google.com/p/modconcat
"""

import re
HREF_PATTERN = re.compile('href="([^"]*)"')
SRC_PATTERN = re.compile('src="([^"]*)"')

from django import template
from django.template import Template
register = template.Library()

from django.conf import settings

def _concat_enabled():
    """ Tests if concatenation is enabled in the settings file. """
    return hasattr(settings, 'ENABLE_CONCAT') and settings.ENABLE_CONCAT

@register.tag
def cssconcat(parser, token):
    """
    Takes a block of one or more <link> elements, concatenates all of the href's together
    into a single href suitable for modconcat. Example:
    
    <link href="/site_media/a.css" rel="stylesheet" type="text/css" /> 
    <link href="/site_media/b.css" rel="stylesheet" type="text/css" /> 
    <link href="/site_media/c.css" rel="stylesheet" type="text/css" /> 
    
    ...becomes...
    
    <link href="/site_media/??a.css,b.css,c.css" rel="stylesheet" type="text/css" />     
    """
    tag_name, basepath = token.split_contents()
    nodelist = parser.parse(('endcssconcat',))
    parser.delete_first_token()
    
    return ConcatCssNode(nodelist, basepath[1:-1]) #strip quotes

@register.tag
def jsconcat(parser, token):
    """
    Takes a block of one or more <script> elements, concatenates all of the src's together
    into a single src suitable for modconcat. Example:

    <script src="/site_media/a.js" type="text/javascript"></script> 
    <script src="/site_media/b.js" type="text/javascript"></script> 
    <script src="/site_media/c.js" type="text/javascript"></script> 

    ...becomes...
    
    <script src="/site_media/??a.js,b.js,c.js" type="text/javascript"></script> 
    """
    tag_name, basepath = token.split_contents()
    nodelist = parser.parse(('endjsconcat',))
    parser.delete_first_token()
    
    return ConcatJavascriptNode(nodelist, basepath[1:-1]) #strip quotes

class ConcatCssNode(template.Node):
    """ Renders the cssconcat template tag """
    def __init__(self, nodelist, basepath):
        self.nodelist = nodelist
        self.basepath = basepath
        
    def render(self, context):
        """ Renders the cssconcat template tag """
        if _concat_enabled():
            output = self.nodelist.render(context)
            basepath = Template(self.basepath).render(context)
            css_paths = HREF_PATTERN.findall(output)
            return u'<link href="%s??%s" rel="stylesheet" type="text/css" />' % \
                (basepath, ','.join(css_paths).replace(basepath, ''))

        return self.nodelist.render(context)

class ConcatJavascriptNode(template.Node):
    """ Renders the jsconcat template tag """
    def __init__(self, nodelist, basepath):
        self.nodelist = nodelist
        self.basepath = basepath

    def render(self, context):
        """ Renders the jsconcat template tag """        
        if _concat_enabled():
            output = self.nodelist.render(context)   
            basepath = Template(self.basepath).render(context)     
            javascript_paths = SRC_PATTERN.findall(output)
            return u'<script src="%s??%s" type="text/javascript"></script> ' % \
                (basepath, ','.join(javascript_paths).replace(basepath, ''))

        return self.nodelist.render(context)