"""
Created on 06.06.2011

@author: christian
"""
import os
import fnmatch

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 _


class Command(BaseCommand):
    """
    classdocs
    """
    can_import_settings = True
    help = _("Compile SCSS rules.")

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

            print _("Compressing CSS for %s") % site.name
            print "Input Dir: %s" % css_input
            print "Output File: %s" % css_output

            try:
                os.makedirs(css_input)
            except OSError:
                pass
            css = ''
            """Read each .css file in the css_input directory, 
            and append their content"""
            for file_name in fnmatch.filter(sorted(os.listdir(css_input)),
                                            '*.css'):
                print '  Adding: %s' % file_name
                with open(os.path.join(css_input, file_name), 'r') as css_file:
                    css += css_file.read()
            with open(css_output, 'w') as css_file:
                css_file.write(self.compress(css))
                # file.write(css)

