/*******************************************************************************
 * Copyright 2019 2Fi Business Solutions Ltd.
 *
 * This code is part of the Core project.
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.core.engine;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.context.support.WebApplicationObjectSupport;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * FreeMarker template engine - a Spring Component Bean
 *
 * @author Patrick
 */
@Component
public class FreeMarkerEngine extends WebApplicationObjectSupport {

	@Autowired
	private FreeMarkerConfigurer freemarkerConfig;

	/**
	 * Generates content from FreeMarker template
	 *
	 * @param template
	 *            the FreeMarker template name (e.g. {@code "example/example.ftl"})
	 * @param model
	 *            the model to be applied to the FreeMarker template, may be null
	 * @return the generated content as a {@code String}, or {@code null} if exceptions occured
	 */
	public String generateFreeMarkerContent(String template, Object model) {
		try {
			Template t = freemarkerConfig.getConfiguration().getTemplate(template);
			return FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
		} catch (TemplateException e) {
			logger.error("Error while processing FreeMarker template ", e);
		} catch (IOException e) {
			logger.error("IOException occured ", e);
		}
		return null;
	}

}
