from django import template
from django.conf import settings
import os

register = template.Library()

def add_vid_to_filename(filename, vid=os.getenv('CURRENT_VERSION_ID', None)):
    """
    Add current version id to passed filename in form:
    filename.ext -> filename.VID.ext
    """
    if not vid:
        return filename
    file_ext = filename.rsplit('.',1)
    if len(file_ext) < 2:
        return file_ext[0]+'.'+vid
    return '.'.join((file_ext[0],vid, file_ext[1]))

def css(parser, token):
    """
    This will use merged css files on production or original ones on development server.

    Usage::

        {% load cssjs %}
        {% css media all.css cssfile1 [cssfile2] .. %} 

    If the code is working on development server, the tag will create several links
    with cssfile1 [cssfile2] etc.
    
    If the code is run on production server, the tag will use all.css and will insert
    version id before file exension.
    
    The HTML output for this will be::

        <link media="all" rel="stylesheet" href="/media/all.1.1.css" type="text/css" />
    """
    tokens = token.contents.split()
    if len(tokens) < 4:
        raise template.TemplateSyntaxError(u"'%r' tag requires at least 3 arguments." % tokens[0])
    if 'Dev' in os.getenv('SERVER_SOFTWARE'):
        return template.TextNode('\n'.join(['<link media="%s" rel="stylesheet" href="%s%s" type="text/css" />' % (tokens[1], settings.MEDIA_URL, css) for css in tokens[3:]]))
    else:
        return template.TextNode('<link media="%s" rel="stylesheet" href="%s%s" type="text/css" />' % (tokens[1], settings.MEDIA_URL, add_vid_to_filename(tokens[2])))

def js(parser, token):
    """
    This will use merged js files on production or original ones on development server.

    Usage::

        {% load cssjs %}
        {% js all.js jsfile1 [jsfile2] .. %} 

    If the code is working on development server, the tag will create several links
    with cssfile1 [cssfile2] etc.
    
    If the code is run on production server, the tag will use all.js and will insert
    version id before file extension.
    
    The HTML output for this will be::
    
        <script type="text/javascript" src="/media/all.1.1.js"></script>
    """
    tokens = token.contents.split()
    if len(tokens) < 3:
        raise template.TemplateSyntaxError(u"'%r' tag requires at least 2 arguments." % tokens[0])
    if 'Dev' in os.getenv('SERVER_SOFTWARE'):
        return template.TextNode('\n'.join(['<script type="text/javascript" src="%s%s"></script>' % (settings.MEDIA_URL, css) for css in tokens[2:]]))
    else:
        return template.TextNode('<script type="text/javascript" src="%s%s"></script>' % (settings.MEDIA_URL, add_vid_to_filename(tokens[1])))

register.tag('css', css)
register.tag('js', js)