package br.mp.mprj.portal.portlet.gestaomensagens.util;


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

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;

import com.liferay.portal.kernel.io.unsync.UnsyncStringWriter;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;

/**
 * Classe utilit&aacute;ria Velocity com base no VelocityUtil do Liferay devido a restri&ccedil;&atilde;o 
 * de n&atilde;o poder utilizar API's do portal-impl.jar que n&atilde;o est&atilde;o expostas
 * em algum .jar utilit&aacute;rio do portal como util-java.jar, etc.
 * @author henriquesimoes
 */
public class VelocityUtil {

    private static final Log _log = LogFactoryUtil.getLog(VelocityUtil.class);
	private static VelocityUtil _instancia = new VelocityUtil();
	
	private VelocityUtil(){}
	
	/**
	 * Carrega o template Velocity em uma String, de acordo com o arquivo especificado no caminho.
	 * 
	 * @param caminho - relativo ao diretorio classes do projeto, ex: "template/email/alerta-workflow.vm".
	 * @return String
	 */
	public static String carregarTemplate(String caminho) throws IOException {
		return StringUtil.read(_instancia.getClass().getClassLoader(), caminho, true);
	}

	/**
	 * Processa o template Velocity.
	 * @param template
	 * @return String - template processado.
	 * @throws Exception
	 */
	public static String processarTemplate(String template) throws Exception {
		return processarTemplate(null, template);
	}
	
	/**
	 * Processa o template Velocity, atribuindo os valores de acordo com o Map.
	 * @param variaveis
	 * @param template
	 * @return String - template processado, ou vazio caso tenha ocorrido algum erro (ser&aacute; registrado no log).
	 * @throws Exception
	 */
	public static String processarTemplate(Map<String, Object> variaveis, String template) {
	    try {
    	   VelocityEngine velocityEngine = new VelocityEngine();
    	    
           velocityEngine.setProperty(
                   RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
                   PropsUtil.get(PropsKeys.VELOCITY_ENGINE_LOGGER));
    
           velocityEngine.setProperty(
                   RuntimeConstants.RUNTIME_LOG_LOGSYSTEM + ".log4j.category",
                   PropsUtil.get(PropsKeys.VELOCITY_ENGINE_LOGGER_CATEGORY));
    
           velocityEngine.init();
    	    
    		VelocityContext context = new VelocityContext();
    		if (variaveis != null) {
    			Iterator<Map.Entry<String, Object>> it = variaveis.entrySet().iterator();
    			while (it.hasNext()) {
    				Map.Entry<String, Object> entry = it.next();
    				String key = entry.getKey();
    				if (Validator.isNotNull(key)) {
    					context.put(key, entry.getValue());
    				}
    			}
    		}
    		UnsyncStringWriter usw = new UnsyncStringWriter();
    		velocityEngine.evaluate(context, usw, VelocityUtil.class.getName(), template);
    		return usw.toString();
	    }
	    catch (Exception ex) {
	        _log.error("Problemas ao processar template Velocity:", ex);
	        return StringPool.BLANK;
	    }
	}
	
}
