# -*- coding: utf-8 -*-
"""
    MoinMoin - macro to specify columns

    As far as the author is concerned, this code is released to the public
    domain, but some restrictions in the MoinMoin COPYING file may apply. Ask a
    lawyer.
    ***********
    This code has not been tested exhaustively. Use at your own risk.
    ***********

    This macro generates containers, that can be used with CSS to create
    columns.

    Usage:
        <<Columns(columnCount, [start|end])>>

        columnCount    2-10 total number of columns (used primarily to calculate column width)

        start          pass "start" as the second argument to define the first column
        
        end            pass "end" as the second argument to define the last column

    Examples:

        <<Columns(3, start)>>
                This text is in the left column.
        <<Columns(3)>>
                This text is in the middle column.
        <<Columns(3)>>
                This text is in the right column.
        <<Columns(3, end)>>


    Demo. Try pasting the above examples into a MoinMoin sandbox page.

    @copyright: Antti Kuntsi <antti@kuntsi.com>
    @license: GNU GPL, see COPYING for details.

    changes:
        12.2007 - conversion to new syntax by Bolesław Kulbabiński
        03.2010 - Moved CSS to inline for easier installation. Autocompute styles and widths to handle arbirtary numbers of columns without manual CSS editing. Updates by Peter Lyons
"""
import string
import sys
import types

from MoinMoin.wikiutil import required_arg

#Feel free to increase this if you really can use more than 10 columns.
#It's just an arbitrary reasonable limit
MAX_COLUMNS = 10
rangeStrings = [str(x) for x in range(1, MAX_COLUMNS + 1)]

#Feel free to adjust this if needed. Could be added as a wiki markup parameter
MARGIN_WIDTH = 1
COLUMN_TEMPLATE = string.Template("""
<!-- output generated by the Columns macro Version 1.8.4 -->
<style>
div.column_${columnCount} {
    float: left;
    width: ${columnWidth}%;
    margin-left: ${marginWidth}%;
}
</style>
<div class="column_${columnCount}">
""")
        
def macro_Columns(macro, columnCount=required_arg(rangeStrings),
        startOrEnd=("", "start", "end")):
    tags = []
    if startOrEnd != "start":
        tags.append("\n</div><!--end column -->\n")
    if startOrEnd != "end":
        columnWidth = int(100 / int(columnCount)) - MARGIN_WIDTH
        tags.append(COLUMN_TEMPLATE.safe_substitute({
            "columnWidth": columnWidth,
            "columnCount": columnCount,
            "marginWidth": MARGIN_WIDTH
            }))
    if startOrEnd == "end":
        tags.append('\n<br clear="left"/>')
    if macro:
        result = [macro.formatter.rawHTML("".join(tags))]
    else:
        result = tags
    return "".join(result)

#Facilititates quick testing on the command line        
if __name__ == "__main__":
    print macro_Columns(None, *sys.argv[1:])
