# GetValues.py
'''
	This macro shows a list of pages
		a) whose names match the given regular expression and
		b) who contain a definition with a certain heading which optionally has
		a value matching a certain re
		

Usage: [[GetValues(PageRE,DefinitionTermRE[,DefinitionValueRE])]]

Examples:
	[[GetValues(.*Service,Host)]] might output the following:
	. FooService
		Host:
			FooHost
	. BarService
		Host:
			BarHost

TODO:

History:
	1.0 First version - MarkusMaier
	1.1 Key is regular expression - MarkusMaier
	1.2 Added optional re as restriction on values - MarkusMaier
	1.3 Multiple matches for one page are collapsed to one list - MarkusMaier
	1.4 Output is now a definition list - MarkusMaier
'''

Dependencies = [1]

import re
from MoinMoin.wikidicts import Dict

def execute(macro,args):
	args = args.split(",")
	page_re = args[0]
	key_re = args[1]

	if (len(args) < 3):
		def_re = ".*"
	else:
		def_re = args[2]

	result = "<ul>"
	isdict = re.compile(page_re, re.UNICODE).search
	iskey = re.compile(key_re, re.UNICODE).search
	isdef = re.compile(def_re, re.UNICODE).search
	dictpages = macro.request.rootpage.getPageList(user='', filter=isdict)
	dictpages.sort()
	for pagename in dictpages:
		dict = Dict(macro.request, pagename)
		page_link = 0
		for key in dict.keys():
			if iskey(key.strip()):
				if isdef(dict.get(key,"")):
					if page_link == 0:
						page_link = 1
						result += "<li>" + macro.formatter.url(1, pagename) + pagename + macro.formatter.url(0) + "<dl>"
					result += "<dt>" + key.strip() + "<dd>" + dict.get(key, "---") + "</dd>"
		if page_link == 1:
			result += "</dl>"
	
	result += "</ul>"
	return macro.formatter.rawHTML(result)
