package kz.cafe.utils;

import java.io.*;
import java.util.*;
import org.apache.commons.logging.*;
import org.apache.velocity.*;
import org.apache.velocity.app.*;

public class VelocityProc{
   private static Log log = LogFactory.getLog(VelocityProc.class);

   private static final String LOG = "[VELOCITY] ";
   
   
   public static String run(String sTemplate, Map<String, Object> context) throws Exception{
      StringWriter writerResult = new StringWriter();
      PrintWriter out = new PrintWriter(writerResult);

      VelocityContext vc = new VelocityContext();
      
      for(String sKey : context.keySet()){
         vc.put(sKey, context.get(sKey));
      }
      
      Properties p = new Properties();
      
      p.put("resource.loader","class");
      p.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");      
      
      //String absolutePath=new File(Thread.currentThread().getContextClassLoader().getResource("").getFile()).getParentFile().getParentFile().getPath();
      //p.put("file.resource.loader.path", absolutePath + "/WEB-INF/classes");
      
//      p.setProperty("file.resource.loader.path", "/opt");
//      Velocity.init( p );
      
      Velocity.init(p);
      

      Template t = Velocity.getTemplate(sTemplate, "UTF-8");
      t.merge(vc, out);
      out.flush();
      out.close();
      
      log.debug(LOG + writerResult.toString());
      
      return writerResult.toString();
   }

}
