# css_functions.py
#
# CSS compressor
#
# Author: Remigijus Jarmalavicius <remigijus@jarmalavicius.lt>
# Copyright (c) Remigijus Jarmalavicius 2009

import re

# Humanize file size from bytes to normal human friendly file size
def humanize_file_size(file_size):
    if file_size > 1024:
        human_size = str("%0.2f" % (float(file_size) / float(1024))) + "KB"
        if file_size / 1024 > 1024:
            human_size = str("%0.2f" % (float(file_size) / float(1024) / float(1024))) + "MB"
            if file_size / 1024 / 1024 > 1024:
                file_size = str("%0.2f" % (float(file_size) / float(1024) / float(1024) / float(1024))) + "GB"
    else:
        human_size = str(file_size) + "B"
    return human_size


# Compress CSS content
def compress_css(css):
    temp_css = css
    temp_css = re.sub('\n+', ' ', temp_css) # replace new lines to space
    temp_css = re.sub('\r+', ' ', temp_css) # replace new lines to space
    temp_css = re.sub('\t+', ' ', temp_css) # remove tab's
    temp_css = re.sub('\/\*[^\*]+\*\/', '', temp_css) # remove comments
    temp_css = re.sub(' *\{ *', '{', temp_css) # strip spaces before and after {
    temp_css = re.sub(' *\} *', '}', temp_css) # strip spaces before and after }
    temp_css = re.sub(' *\: *', ':', temp_css) # strip spaces before and after :
    temp_css = re.sub(' *\; *', ';', temp_css) # strip spaces before and after ;
    temp_css = re.sub(' *\, *', ',', temp_css) # remove spaces before and after ,
    temp_css = re.sub('\;\}', '}', temp_css) # remove ; before }
    temp_css = re.sub(' + ', ' ', temp_css) # strip multiple spaces
    temp_css = re.sub('\}', '}\n', temp_css) # after } print new line symbol
    ret_css = ''
    for line in re.split('\n', temp_css):
        if line.strip() == '':
            continue
        ret_css = ret_css + '\n' + line
    return ret_css[1:len(ret_css)]

# Decompress CSS code and format it
def decompress_css(css):
    temp_css = css
    temp_css = re.sub('\{', ' {\n\t', temp_css)
    temp_css = re.sub(';', ';\n\t', temp_css)
    temp_css = re.sub('\}', ';\n}', temp_css)
    temp_css = re.sub(':', ': ', temp_css)
    temp_css = re.sub(',', ', ', temp_css)
    return temp_css

