package org.jerrymouse.cc.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class ResourceBuilder {

	private ResourceBuilder() {
	}

	public static ResourceBuilder getResourcesBuilder() {
		return new ResourceBuilder();
	}

	public InputStream load(String path) {
		return getClass().getClassLoader().getResourceAsStream(path);
	}

	public String vm(String filename, Map<String, Object> map) {
		Reader reader;
		StringWriter writer = null;
		try {
			reader = new InputStreamReader(load("vm/" + filename));
			VelocityContext context = new VelocityContext();
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				context.put(entry.getKey(), entry.getValue());
			}
			writer = new StringWriter();
			Velocity.evaluate(context, writer, filename, reader);

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return writer.toString();
	}
}
