#!/usr/bin/env python
# -*- coding: UTF-8 -*-

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

register = template.Library()

class SassNode(template.Node):
    def __init__(self, format_string):
        self.format_string = format_string
        self.input = os.path.join(settings.SITE_ROOT, 'sass')
        self.output = os.path.join(settings.SITE_ROOT, 'static')
        self.input_file = None
        self.output_file = None
        self.__create_sass()
        self.__create_css()

    def __clean(self):
        """
        清理,如果没有相应的sass,则清理掉css
        本功能有些极端,暂时不提倡,提倡用手工清理没用的css
        """
        pass

    def __create_sass(self):
        path_list = self.format_string.split('.')
        input_path = os.path.join(self.input, *path_list[:-1])
        if not os.path.isdir(input_path):
            os.makedirs(input_path)
        input_file = os.path.join(input_path, '%s.sass'%path_list[-1])
        if not os.path.isfile(input_file):
            os.mknod(input_file)
        self.input_file = input_file

    def __create_css(self):
        path_list = self.format_string.split('.')
        output_path = os.path.join(self.output, *path_list[:-1])
        if not os.path.isdir(output_path):
            os.makedirs(output_path)
        output_file = os.path.join(output_path, '%s.css'%path_list[-1])
        if not os.path.isfile(output_file) or os.path.getmtime(self.input_file)>os.path.getmtime(output_file):
            os.system("/usr/local/ruby/bin/sass %s %s" % (self.input_file, output_file))

    def render(self, context):
        path_list = self.format_string.split('.')
        output_url = ['static']
        output_url.extend(path_list[:-1])
        output_url.append('%s.css'%path_list[-1])
        output_url = '/' + '/'.join(output_url)
        return '<link rel="stylesheet" type="text/css" href="%s" />' % output_url


@register.tag
def sass(parser, token):
    try:
        tag_name, resource = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, '%s tag requires a single argument.' % token.contents.split()[0]
    if not (resource[0]==resource[-1] and resource[0] in ('"',"'")):
        raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
    return SassNode(resource[1:-1])