package com.inkasso.factoring.code.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

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


public class FreemarkerUtils {
	
	private static Configuration cfg = null;
	static {
		cfg = new Configuration(Configuration.VERSION_2_3_29);
		cfg.setClassForTemplateLoading(FreemarkerUtils.class, "/code");
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        cfg.setWrapUncheckedExceptions(true);
	}
	public static String getTemplate(String template, Map<String,Object> map) throws IOException, TemplateException {
        Template temp = cfg.getTemplate(template);
        StringWriter stringWriter = new StringWriter();
        temp.process(map, stringWriter);
        return stringWriter.toString();
    }
	
	public static void  createFile(String templateName, String url, Map rootMap) throws IOException {
		Template t =cfg.getTemplate(templateName+".ftl");
		File file = new File(url.substring(0, url.lastIndexOf(File.separator)));
		System.out.println("----"+url.substring(0, url.lastIndexOf(File.separator))+"------");
		System.out.println("----"+url+"------");
		if(!file.exists()){
			file.mkdirs();
		}
		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(url),"utf-8"));
	    try {
			t.process(rootMap, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		}finally{
			if(out!=null) {
				out.close();
			}
		}
	}
}
