package lc.mecha.exec;

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.Velocity;
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.OutputStream;
import java.io.OutputStreamWriter;

/**
 * Implements a {@link BatchTask} for the Velocity template engine.
 * <p>
 * Limitations: This task is unaware of any application-requirements, so take care that your Velocity template
 * is proper for your application. For example, ensure the line-endings are correct, and the last command has
 * a line ending, if required by the application.
 *
 * @author Alex Leigh
 */
public class VelocityTask implements BatchTask {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(VelocityTask.class);
    private final static String KEY_TASK = "task";
    private final String templatePath;

    // TODO Do we really have to?
    static {
        Velocity.init();
    }

    public VelocityTask(String templatePath) {
        this.templatePath = templatePath;
    }

    @Override
    public void writeScript(OutputStream os) throws IOException {
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        Template sequenceTemplate = ve.getTemplate(templatePath);
        VelocityContext ctx = new VelocityContext();
        ctx.put(KEY_TASK, this);
        OutputStreamWriter ow = new OutputStreamWriter(os);
        sequenceTemplate.merge(ctx, ow);
        ow.close();
    }

    @Override
    public void finished(String result) throws IOException {
        // Intentionally Blank
    }
}