package com.peterphi.std.guice.freemarker;

import com.google.inject.Inject;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class FreemarkerTemplater
{
	private Map<String, Object> data = new HashMap<String, Object>();
	private final Configuration config;

	private final String templatePrefix;
	private final String templateSuffix;

	@Inject
	public FreemarkerTemplater(Configuration config)
	{
		this(config, "", ".ftl");
	}

	public FreemarkerTemplater(Configuration config, final String templatePrefix, final String templateSuffix)
	{
		this.config = config;
		this.templatePrefix = templatePrefix;
		this.templateSuffix = templateSuffix;
	}


	public FreemarkerCall template(String name)
	{
		// Load the template
		final Template template;
		try
		{
			final String templateName = templatePrefix + name + templateSuffix;

			template = config.getTemplate(templateName);
		}
		catch (IOException e)
		{
			throw new IllegalArgumentException("Could not load template " + name + ": " + e.getMessage(), e);
		}

		final FreemarkerCall call = new FreemarkerCall(template);

		// Populate shared data
		call.setAll(data);

		return call;
	}

	public void set(String key, Object value)
	{
		data.put(key, value);
	}

	public void setAll(Map<String, Object> data)
	{
		this.data.putAll(data);
	}
}

@@ -444,16 +444,17 @@
 uffix;%0A%0A
+%0A
 %09@Inject
@@ -535,24 +535,25 @@
 .ftl%22);%0A%09%7D%0A%0A
+%0A
 %09public Free
@@ -756,24 +756,491 @@
 uffix;%0A%09%7D%0A%0A%0A
+%09public Template buildMemoryTemplate(final String name, final String templateStr)%0A%09%7B%0A%09%09try%0A%09%09%7B%0A%09%09%09return new Template(name, templateStr, config);%0A%09%09%7D%0A%09%09catch (IOException e)%0A%09%09%7B%0A%09%09%09throw new RuntimeException(%22Error parsing template from input string! %22 + e.getMessage(), e);%0A%09%09%7D%0A%09%7D%0A%0A%0A%09public FreemarkerCall template(Template template)%0A%09%7B%0A%09%09final FreemarkerCall call = new FreemarkerCall(template);%0A%0A%09%09// Populate shared data%0A%09%09call.setAll(data);%0A%0A%09%09return call;%0A%09%7D%0A%0A%0A
 %09public Free
@@ -1599,132 +1599,38 @@
 %0A%0A%09%09
-final FreemarkerCall call = new FreemarkerCall(template);%0A%0A%09%09// Populate shared data%0A%09%09call.setAll(data
+return template(template
 );%0A
-%0A%09%09return call;%0A
 %09%7D
+%0A
 %0A%0A%09p
@@ -1701,16 +1701,17 @@
 e);%0A%09%7D%0A%0A
+%0A
 %09public 

Allow FreemarkerTemplater to be used to use in-memory template sources