import urlparse
import os
from subprocess import call
 
from django import template
from django.contrib.sites.models import Site
from django.conf import settings
from django.utils.importlib import import_module
 
try:
    set
except NameError:
    import Set as set
 
register = template.Library()
 
def _absolute_url(url):
    if url.startswith('http://') or url.startswith('https://'):
        return url
    domain = Site.objects.get_current().domain
    return 'http://%s%s' % (domain, url)
 
def _get_tagger(path=settings.COAT_TAGGER):
    where, name = path.rsplit('.', 1)
    base, module = where.rsplit('.', 1)
 
    module = import_module('.%s' % module, base)
 
    return getattr(module, name)
 
tagger = _get_tagger()
 
def _compile(source):
    dirname, filename = os.path.split(source)
    name, ext = os.path.splitext(filename)
    ext = ext[1:]
 
    source_fullpath = os.path.join(settings.MEDIA_ROOT, source)
 
    try:
        target_ext, command = settings.COAT_COMPILERS[ext]
    except KeyError:
        return source_fullpath, source, False
 
    target = os.path.join(
        dirname,
        settings.COAT_COMPILED_PATTERN % {'ext': target_ext, 'name': name}
    )
 
    target_fullpath = os.path.join(settings.COAT_COMPILED_ROOT or settings.MEDIA_ROOT, target)
 
    def _call():
        call(
            (command % {'source': source_fullpath, 'target': target_fullpath}).split(' '),
            close_fds=True
        )
 
    try:
        if not os.path.exists(target_fullpath):
            compiled_base = os.path.dirname(target_fullpath)
            if not os.path.exists(compiled_base):
                os.makedirs(compiled_base)
            _call()
        elif os.path.getmtime(source_fullpath) > os.path.getmtime(target_fullpath):
            _call()
    except OSError:
        return source_fullpath, source, False
 
    return target_fullpath, target, True
 
@register.simple_tag
def coat(filename, flags=''):
    """
    Initial concept by Ivan Sagalaev (http://softwaremaniacs.org/about/)
    """
    fullname, filename, done = _compile(filename)
 
    flags = set(f.strip() for f in flags.split(','))
    url = urlparse.urljoin(
        done and (settings.COAT_COMPILED_URL or settings.MEDIA_URL) or settings.MEDIA_URL,
        filename
    )
    if 'absolute' in flags:
        url = _absolute_url(url)
 
    if (filename.endswith('.css') or filename.endswith('.js')) and 'no-tag' not in flags:
        if os.path.exists(fullname):
            tag = tagger(fullname)
            if tag:
                url += '?%s' % tag
    return url