package eu.nets.sis.idrights.demoapp.util;

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

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class PageUIUtil {
	
private static final Logger LOGGER = LogManager.getLogger(PageUIUtil.class);
	
	private static Configuration freemarkerConfig;
	
	public static void streamPage(Map<String, Object> data, String templateName, PrintWriter out) {
		initializeFreemarker();
		try {
			Template temp = freemarkerConfig.getTemplate(templateName);
			temp.process(data, out);
		} catch (IOException | TemplateException e) {
			LOGGER.error("Got exception while loading page.", e);
		}
	}
	
	private synchronized static void initializeFreemarker() {
        if (freemarkerConfig != null)  {
            return;
        }
        freemarkerConfig = new Configuration(Configuration.VERSION_2_3_30);
        freemarkerConfig.setDefaultEncoding("UTF-8");
        freemarkerConfig.setClassForTemplateLoading(PageUIUtil.class, "/");
        freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    }

}
