"""
Inserts a link for the parent-tree of the current page.

This only applies to pages with a forward-slash (/) in their name.
If there is no forward-slash present, the macro defaults to displaying
the name of the current page (with no href tag).

e.g.: an entry named Top/Middle/Bottom would result in the following
psuedo-HTML output:

<a href='site/wiki/Top'>Top</a>&nbsp;-&nbsp;
<a href='site/wiki/Top/Middle'>Middle</a>&nbsp;-&nbsp;
Bottom

Only one argument is allowd. The argument is a string of equal signs
indicating the value of the wiki header to simulate. For instance,
given [[ParentLinkage(=)]], the entire linkage output would be wrapped
in an <h1> heading tag with the appropriate ID attribute set. Thus,
given the above page name of Top/Middle/Bottom, the result would be
something like this:

<h1 id='Top-Middle-Bottom'>
<a href='site/wiki/Top'>Top</a>&nbsp;-&nbsp;
<a href='site/wiki/Top/Middle'>Middle</a>&nbsp;-&nbsp;
Bottom
</h1>

Up to four equal signs may be present.

Written by: Kevin C. Krinke <kevin@krinke.ca>
Inspired by (and based on) the ParentLink macro.
"""

import re
from StringIO import StringIO

def split_camel_case(string):
    result = string
    #: let's break up "ThisThat" into "This That"
    while re.search( '([A-Z]+[a-z]+)([A-Z]+)', result ):
        result = re.sub( r'([A-Z]+[a-z]+)([A-Z]+)', r'\1 \2', result )
    #: let's break up "UIExamples" into "UI Examples"
    while re.search( '([A-Z]+[A-Z][a-z]+)', result ):
        result = re.sub( r'([A-Z]+)([A-Z][a-z]+)', r'\1 \2', result )
    #: let's fix "And" to read "and"
    while re.search( ' And ', result ):
        result = re.sub( ' And ', ' and ', result )
    #: let's fix "Of" to read "of"
    while re.search( ' Of ', result ):
        result = re.sub( ' Of ', ' of ', result )
    return result

def execute(hdf, args, env):
    db = env.get_db_cnx()
    cursor = db.cursor()

    buf = StringIO()

    pg_name = hdf.getValue('wiki.page_name', '')

    h_id = ''
    h_num = 0
    if args:
        eqs = re.search( '^(\=+)$', args[0] ).group( 1 )
        if eqs:
            h_id = re.sub( '/', '-', pg_name )
            h_num = len( eqs )
            if h_num > 4:
                h_num = 4 #: cap at <h4>
            buf.write( '<h%d id="%s">' % ( h_num, h_id ) )

    match = re.findall( "([^/]+)/", pg_name )
    if len( match ):
        build = ""
        for i in range( len( match ) ):
            s = match[i]
            if len( build ):
                build = build + "/" + s
            else:
                build = s
            buf.write( '<a class="wiki" href="%s">' % env.href.wiki( build ) )
            buf.write( split_camel_case( s ) )
            buf.write( "</a>&nbsp;-&nbsp;" )

        last = re.search( "/([^/]+)$", pg_name ).group( 1 )
        last = split_camel_case( last )
        buf.write( last )
    else:
        buf.write( split_camel_case( pg_name ) )

    if h_num:
        buf.write( '</h%d>' % h_num )
        
    return buf.getvalue()

