package com.bennavetta.vetinari.template.groovy;

import com.bennavetta.vetinari.template.Template;
import com.bennavetta.vetinari.template.TemplateEngine;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import groovy.text.SimpleTemplateEngine;

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

/**
 * Render templates with Groovy's SimpleTemplateEngine.
 */
public class GroovyTemplateEngine implements TemplateEngine
{
	// TODO: I think this is the only part of vetinari-core using Groovy. Maybe put it in vetinari-integration?

	private groovy.text.TemplateEngine templateEngine;

	public GroovyTemplateEngine()
	{
		this.templateEngine = new SimpleTemplateEngine();
	}

	@Override
	public Template compile(String source)
	{
		try
		{
			return new GroovyTemplate(templateEngine.createTemplate(source));
		}
		catch (ClassNotFoundException | IOException e)
		{
			throw Throwables.propagate(e);
		}
	}

	@Override
	public String getName()
	{
		return "groovyTemplate";
	}

	@Override
	public Iterable<String> getFileExtensions()
	{
		return ImmutableList.of("gtpl");
	}

	private static class GroovyTemplate implements Template
	{
		private final groovy.text.Template template;

		public GroovyTemplate(groovy.text.Template template)
		{
			this.template = template;
		}

		@Override
		public String render(Map<String, Object> variables)
		{
			return template.make(variables).toString();
		}
	}
}

@@ -239,16 +239,55 @@
 leList;%0A
+import com.google.common.collect.Maps;%0A
 import g
@@ -1417,24 +1417,130 @@
 iables)%0A%09%09%7B%0A
+%09%09%09// Make a copy since SimpleTemplateEngine's internals modify the binding, which can be an ImmutableMap%0A
 %09%09%09return te
@@ -1551,16 +1551,32 @@
 te.make(
+Maps.newHashMap(
 variable
@@ -1577,16 +1577,17 @@
 riables)
+)
 .toStrin

fix GroovyTemplateEngine