package net.waltzstudio.base.generator.util;

import java.io.Writer;
import java.util.Map;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class TemplateUtil {

	private static final Object lock = new Object();

	private static Configuration configuration;
	private static Configuration getConfiguration() {
		if (configuration == null) {
			synchronized (lock) {
				configuration = new Configuration();
			}
		}
		return configuration;
	}

	public static Writer process(String templatePath, String templateName, Map<String, Object> rootMap, Writer out) {
		Configuration c = getConfiguration();
		try {
			c.setTemplateLoader(new ClassTemplateLoader(TemplateUtil.class, templatePath));
			c.setObjectWrapper(new DefaultObjectWrapper());
			Template tmpl = c.getTemplate(templateName);
			tmpl.process(rootMap, out);
			return out;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
