"""	Trac Macro for inclusion of reverse navigation 

        COPYRIGHT(C): Anders Jansson, 2005, anders.jansson@kastanj.net

	You are hereby free to do whatever You find appropriate with this code,
	except sue me, even if it screws up Your life. If You find it useful
	and appreciate it, send me an email and tell me so, otherwise don't
	bother. Please leave a reminder of the original author if it resembles
	the original code.
"""

from StringIO import StringIO

def execute(hdf, args, env):
    """ AutoNav(arg) finds all references in the wiki section to this Document
	and shows them in a sorted list.

	Used with no arguments only produces a list from the database. Arguments
	sent to AnutoNav will be merged inside the list too. Separate the
	arguments with comma.

	Example:
	    [[AutoNav()]]	-> only references
	    [[AutoNav(MyPage)]]	-> references merged and sorted with MyPage
	    [[AutoNav(MyPage, MyPageToo, MyPageThree)]]
				-> references merged with MyPage(|Too|Three)
    """

    db = env.get_db_cnx()
    cursor = db.cursor()
    buf = StringIO()

    # get the refere page name
    thispage = hdf.getValue('wiki.page_name', '')

    # process arguments
    pages = []
    if args:
	pages = args.split(','); # this is the split condition

    # query to get the latest version of a page
    query = """
	SELECT w1.name 
	FROM wiki w1, 
	    (
		SELECT name, MAX(version) AS version 
		FROM wiki 
		GROUP BY name
	    ) w2
	WHERE
	    w1.version = w2.version AND
	    w1.name = w2.name AND
	    w1.text LIKE \'%%%s%%\'
    	ORDER BY w1.name""" % thispage

    # TODO: use named parameters
    cursor.execute(query)

    # for each answer store in page
    while 1:
        row = cursor.fetchone()
        if row == None or row[0] == thispage:
            break
	pages.append(row[0])

    pages.sort()

    # get the references to each list
    outlist = []
    for page in pages:
	out = '<a href="%s">%s</a>' % (env.href.wiki(page), page)
	outlist.append(out)

    # format the list
    buf.write('<strong>Navigation:</strong> ( ')
    buf.write(", ".join(outlist))
    buf.write(')\n')

    return buf.getvalue()


