package lc.mecha.exec;

/**
 * This class provides a reference implementation for running an external process to process a batch script. The
 * actual process is undefined, and this class is widely applicable for automating tools.
 *
 * @author Alex Leigh
 */
public class BatchExecutor {
    private final LocalExecutor le = new LocalExecutor();
    private final String cmd;
    private final String[] args;

    /**
     * Create a new batch executor for the given command and arguments.
     */
    public BatchExecutor(String cmd, String[] args) {
        this.cmd = cmd;
        this.args = args;
    }

    /**
     * Attempt to synchronously execute the given task and return the result to the caller.
     */
    public void exec(BatchTask task) throws Exception {
        try (ProcessExecution pe = le.execute(cmd, args)) {
            task.writeScript(pe.getOutputStream());
            pe.getOutputStream().flush();
            task.finished(pe.drainInput());
        }
    }
}
