"""
Allow Trac to support templates for wiki-pages

Example:
{{{
 [[ChooseTemplate]]
 [[ChooseTemplate(templates)]]
}}}
The argument has to point to a wikipage whose subpages are the templates.
If no argumnent is given, a default argument of "WikiTemplates" is assumed.
"""

from StringIO import StringIO
import trac.perm
from trac.util import TracError
from trac.wiki.model import WikiPage

"""
TODO:
- consider removing the links in the preview -> wikipreview = hdf.getValue("args.preview", "")
- do some sanity checks on the arguments
"""

def execute(hdf, args, env):
	if hdf.getValue('macro.blog.rendering', '0') == '1':
		# I do not want to replace the blog main page!		return ""
	if cannotChangeWiki(hdf, env):
		TracError("Insufficient privileges to choose a template")
	
	templateToUse = hdf.getValue("args.useTemplate", "")
	if templateToUse:
		insertTemplate(hdf, env, templateToUse)
		return pageReloadCode()
	
	templateBasePath = args or "WikiTemplates"
	return renderTemplateChooser(env, templateBasePath)

def cannotChangeWiki(hdf, env):
	authname= hdf.getValue("trac.authname", "anonymous")
	readonlypage= bool(hdf.getValue("wiki.readonly", "0"))
	perm= trac.perm.PermissionCache(env, authname)
	canChange= perm.has_permission('WIKI_CREATE') \
			or perm.has_permission('WIKI_EDIT')
	if readonlypage:
		canChange= perm.has_permission('WIKI_ADMIN') \
				or perm.has_permission('TRAC_ADMIN')
	return not canChange


def insertTemplate(hdf, env, templateToUse):
	pagename= hdf.getValue("wiki.page_name", "")
	authname= hdf.getValue("trac.authname", "anonymous")
	page = WikiPage(env, pagename)
	page.text = getTemplate(env, templateToUse)
	page.version += 1
	# TODO: How do we get remote_addr from a macro? (the last argument)
	page.save(authname, 'Template '+templateToUse+' applied', None)


def pageReloadCode():
	# Ugly hack... is there a way to load the modified wikipage directly?
	return "<a href='?action=edit' id='templateAppliedLink'>" \
			"Template applied, please start editing</a>" \
			"<script type='text/javascript'> window.location = " \
			"document.getElementById('templateAppliedLink').href </script>"


def renderTemplateChooser(env, templateBaseSite):
	templates = getTemplates(env, templateBaseSite)
	out = StringIO()
	
	out.write("<ul>")
	for template in templates:
		out.write("<li> <a href='?useTemplate=" + template + "'>" + template + "</a></li>")
	out.write("</ul>")
	
	return out.getValue()


def getTemplates(env, templateBaseSite):
	sql = "SELECT DISTINCT name from wiki where name like '%s/%%' order by name asc" % templateBaseSite
	cursor = env.get_db_cnx().cursor()
	cursor.execute(sql)

	result = []
	while 1:
		rowName = cursor.fetchone()
		if rowName == None: # this stinks
			break
		result.append(rowName[0])
	return result


def getTemplate(env, pageName):
	return WikiPage(env, pageName).text
