#!/usr/bin/env py
"""
This script modifies the Trac CSS files to restrict their scope inside a specific container.

It makes use of http://packages.python.org/cssutils/README.html

for testing, you can do
csstidy trac-orig.css --preserve_css=true --template=low --silent=true | sed s/\\t/\ \ /g > trac-tidy.css
"""

import os
import pkg_resources
import sys

import cssutils

container_id = '#trac-container'


def new_part(part):
    words = part.split()
    if any(w.startswith('body') for w in words):
        return ' '.join('body %s' % container_id if p=='body' else p for p in words)
    elif any(w.startswith('html') for w in words):
        return ' '.join('html %s' % container_id if p=='html' else p for p in words)
    return '%s %s' % (container_id, part)



def update_rule(rule):
    rule.selectorText = ','.join(new_part(p) for p in rule.selectorText.split(','))
    for css_property in rule.style:
        css_property.value = css_property.value.replace('../', '../../common/')


def process_css(body):
    cssutils.ser.prefs.indent = ' '*2
    cssutils.ser.prefs.indentClosingBrace = False
    cssutils.ser.prefs.listItemSpacer = ''
    cssutils.ser.prefs.omitLastSemicolon = False
    cssutils.ser.prefs.omitLeadingZero = True
    cssutils.ser.prefs.propertyNameSpacer = ''

    sheet = cssutils.parseString(body)
    for rule in sheet:
        if isinstance(rule, cssutils.css.CSSStyleRule):
            update_rule(rule)
        elif isinstance(rule, cssutils.css.cssmediarule.CSSMediaRule):
            for subrule in rule:
                if isinstance(subrule, cssutils.css.CSSStyleRule):
                    update_rule(subrule)

    output = sheet.cssText
    output = output.replace(' {', '\n{')
    output = output.replace('}', '}\n')
    return output.rstrip('\n')




def run(dirpath):
    if not os.path.isdir(dirpath):
        raise ValueError('Not a directory: %s' % dirpath)

    # code.css first, as it is included by others
    allfiles = sorted(os.listdir(dirpath), key=lambda x: (not x.startswith('code.'), x))

    target_dir = pkg_resources.resource_filename('penelope.trac', 'htdocs/rescoped-css')
    os.chdir(target_dir)

    for fname in allfiles:
        with open(os.path.join(dirpath, fname)) as fin:
            print fname
            out = process_css(body=fin.read())
            with open(os.path.join(target_dir, fname), 'w') as fout:
                fout.write('/* This file has been automatically generated by trac-rescope. Do not edit. */\n')
                fout.write(out)
    print 'done.'



if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Usage: %s [egg | /path/to/trac/htdocs/css]' % sys.argv[0])
        sys.exit(10)

    if sys.argv[1] == 'egg':
        htdocs = pkg_resources.resource_filename('trac', 'htdocs')
        dirpath = os.path.join(htdocs, 'css')
    else:
        dirpath = sys.argv[1]
    print 'Processing CSS from %s...' % dirpath
    run(dirpath=dirpath)



