"""
Created on 06.06.2011

@author: christian
"""
import fnmatch
import os

from django.conf import settings
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext as _
import jsmin


class Command(BaseCommand):
    """
    classdocs
    """
    can_import_settings = True
    help = _("Reads raw CSS from stdin, and writes compressed CSS to stdout.")

    def handle(self, *args, **options):
        JS_ROOT = os.path.join(settings.STATICFILES_DIRS[0], 'js')
        for site in Site.objects.all():
            js_input = os.path.join(JS_ROOT, site.domain)
            js_output = '%s/%s.js' % (JS_ROOT, site.domain.replace('.', '_'))

            print _("Compressing JavaScript for %s") % site.name
            print "Input Dir: %s" % js_input
            print "Output File: %s" % js_output

            try:
                os.makedirs(js_input)
            except OSError:
                pass
            output = ''
            # Read each .js file in the js_input directory, and append their
            # content
            js_files = fnmatch.filter(sorted(os.listdir(js_input)), '*.js')
            for file_name in js_files:
                print "  Adding: %s..." % file_name
                input_file_name = os.path.join(js_input, file_name)
                with open(input_file_name, 'r') as input_file:
                    output += input_file.read()
            with open(js_output, 'w') as output_file:
                output_file.write(jsmin.jsmin(output))
