# -*- coding: iso8859-1 -*-
#
# Author: Juanma Barranquero
#
# Ideas and syntax heavily lifted from Jan Finell's LegendBox.py wikiprocessor
#

'''
A Trac wiki-processor to display text as a striped listing.

The output is enclosed in a <pre> block of class "striped",
and each line in a <div> block of alternating "even-stripe"
and "odd-stripe" classes. You *must* set this classes up in
your templates/site_css.cs file, or alternatively use the
processor arguments "box-style", "even-style" and "odd-style".

The "number" argument allows automatic numbering of lines;
it accepts three args: a Python-style format (quotes and all),
the initial number for the first line, and the step between
numbers. If no format is passed, there is no automatic
numbering; otherwise, the start and step arguments default to 1.

Example:

{{{
#!Striped
#!number: " %3d ", 100, 10
#!box-style: border: thick solid #C0C0C0; margin: 20px; width: 70%;
#!even-style: background-color: #DAC0DA;
...text here...
}}}
'''

from trac.util import escape, lstrip, rstrip
from StringIO import StringIO

def execute(hdf, text, env):

    def clean(text):
        return lstrip(rstrip(text, ' \r'), ' ')

    def stylize(style):
        return ' style="%s"' % escape(clean(style))

    bstyle = ''
    estyle = ''
    ostyle = ''
    format = None
    start  = 1
    step   = 1
    line   = ''
    offset = 0

    lines = text.split('\n')

    for l in lines[:4]:
        if l.startswith('#!number:'):
            args = l[9:].split(',')
            format = escape(clean(args[0]).split('"',2)[1])
            if len(args) > 1: start = int(args[1])
            if len(args) > 2: step = int(args[2])
        elif l.startswith('#!box-style:'):
            bstyle = stylize(l[12:])
        elif l.startswith('#!even-style:'):
            estyle = stylize(l[13:])
        elif l.startswith('#!odd-style:'):
            ostyle = stylize(l[12:])
        else:
            break
        offset += 1

    buf = StringIO()
    buf.write('<pre class="striped"%s>' % bstyle)

    for i in range(offset, len(lines)-1):
        if (i - offset) % 2:
            alt = 'odd'
            style = ostyle
        else:
            alt = 'even'
            style = estyle
        if format:
            line = format % start
            start += step
        buf.write('<div class="%s-stripe"%s>%s%s</div>' % (alt, style, line, escape(lines[i])))

    buf.write('</pre>')
    return buf.getvalue()
