package it.enea.cruise.controller;

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

import java.io.*;
import java.util.Map;

public class FreeMarkerUtils {

    static Configuration cfg;
    static {
        /* ------------------------------------------------------------------------ */
        /* You should do this ONLY ONCE in the whole application life-cycle:        */

        /* Create and adjust the configuration singleton */
        cfg = new Configuration(Configuration.VERSION_2_3_29);
        try {
            cfg.setDirectoryForTemplateLoading(
                    new File(FreeMarkerUtils.class.getClassLoader().getResource("templates").getPath())
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Recommended settings for new projects:
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        cfg.setWrapUncheckedExceptions(true);
        cfg.setFallbackOnNullLoopVariable(false);
    }

    public static String getHtml(String viewName, Map<String, Object> data) {
        try {
            /* Get the template (uses cache internally) */
            Template temp = cfg.getTemplate(viewName);

            /* Merge data-model with template */
            //Writer out = new OutputStreamWriter(System.out);
            StringWriter out = new StringWriter();
            temp.process(data, out);
            // Note: Depending on what `out` is, you may need to call `out.close()`.
            // This is usually the case for file output, but not for servlet output.
            return out.getBuffer().toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}