package lc.mecha.http.velocity;

import lc.mecha.http.server.HttpTransaction;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Properties;

public class VelocityHttpProcessor {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(VelocityHttpProcessor.class);
    private final VelocityEngine ve = new VelocityEngine();

    public VelocityHttpProcessor() {
        final Properties props = new Properties();
        props.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        props.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init(props);
    }

    public void process(String templatePath, VelocityContext vc, HttpTransaction txn) throws IOException {
        final Template velociraptor = ve.getTemplate(templatePath);

        logger.info("Processing template. [fn: {}]", templatePath);

        try (OutputStreamWriter javaPw = new OutputStreamWriter(txn.httpServletResponse.getOutputStream())) {
            velociraptor.merge(vc, javaPw);
        }
    }
}