from StringIO import StringIO
from trac.util.html import Markup
from trac.wiki.formatter import Formatter 
from trac.wiki.macros import WikiMacroBase

class WikiIncludeMacro(WikiMacroBase):
	def expand_macro(self, formatter, name, args):
		
		args = args.split('|')
		
		if len(args) < 1 :
			return '';
			
		target = args[0]
		db = self.env.get_db_cnx()
		
		sql = "SELECT text from wiki where name = '%s' order by version desc limit 1" % target
		cs = db.cursor()
		cs.execute(sql)
		
		row = cs.fetchone()
		
		if row == None:
			return ''
		
		text = row[0]
		
		if len(args) > 1 :
			i = 0
			for arg in args:
				if i > 0 :
					text = text.replace('{{%d}}' % (i-1), unicode(args[i]))
				i += 1
		
		out = StringIO()
		Formatter(formatter.env, formatter.context).format(text, out)
		return Markup(out.getvalue())

