/**
 * Copyright (c) 2007-2016 SAIC. All Rights Reserved.
 * This software is published under the terms of the SAIC IS Dept.
 * 
 * @Project: safe4j-core
 * @Title: FreeMarkerUtils.java
 * @Package com.saicmotor.framework.utils
 * @Description: 
 *
 * @CreateDate : 2016年4月19日
 * @CreateBy   : kojrf
 */

package com.saicmotor.framework.utils;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

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

/**
 * @ClassName: FreeMarkerUtils
 * @Description: 
 * @author kojrf
 * @date 2016年4月19日 上午10:02:09
 */

public class FreeMarkerUtils {


	public static String renderString(String templateString, Map<String, ?> model) {
		try {
			StringWriter result = new StringWriter();
			Template t = new Template("name", new StringReader(templateString), new Configuration());
			t.process(model, result);
			return result.toString();
		} catch (Exception e) {
			throw ExceptionUtils.unchecked(e);
		}
	}

	public static String renderTemplate(Template template, Object model) {
		try {
			StringWriter result = new StringWriter();
			template.process(model, result);
			return result.toString();
		} catch (Exception e) {
			throw ExceptionUtils.unchecked(e);
		}
	}

	public static Configuration buildConfiguration(String directory) throws IOException {
		Configuration cfg = new Configuration();
		Resource path = new DefaultResourceLoader().getResource(directory);
		cfg.setDirectoryForTemplateLoading(path.getFile());
		return cfg;
	}
	
	public static void main(String[] args) throws IOException {
//		// renderString
//		Map<String, String> model = com.google.common.collect.Maps.newHashMap();
//		model.put("userName", "calvin");
//		String result = FreeMarkerUtils.renderString("hello ${userName}", model);
//		System.out.println(result);
		// renderTemplate
//		Configuration cfg = FreeMarkerUtils.buildConfiguration("classpath:/");
//		Template template = cfg.getTemplate("testTemplate.ftl");
//		String result2 = FreeMarkerUtils.renderTemplate(template, model);
//		System.out.println(result2);
		
//		Map<String, String> model = com.google.common.collect.Maps.newHashMap();
//		model.put("userName", "calvin");
//		String result = FreeMarkerUtils.renderString("hello ${userName} ${r'${userName}'}", model);
//		System.out.println(result);
	}
	

}
