package lc.mecha.exec;

import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import lc.mecha.util.IOUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * A straightforward implementation of the {@link ProcessExecution} interface. This implementation is currently
 * used by {@link LocalExecutor}.
 *
 * @author Alex Leigh
 */
public class ProcessExecutionImpl implements ProcessExecution{
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(ProcessExecutionImpl.class);
    private final InputStream input;
    private final OutputStream output;
    private final InputStream error;

    public ProcessExecutionImpl(InputStream input, OutputStream output, InputStream error) {
        this.input = input;
        this.output = output;
        this.error = error;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return input;
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return output;
    }

    @Override
    public InputStream getErrorStream() throws IOException {
        return error;
    }

    @Override
    public String drainInput(Charset set) throws IOException {
        return IOUtil.readAll(input, set);
    }

    @Override
    public String drainInput() throws IOException {
        return drainInput(Charset.defaultCharset());
    }

    @Override
    public int getReturnCode() {
        return 0;
    }

    @Override
    public void close() {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            error.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
