package com.atlassian.bitbucket.scm.ssh;

import com.atlassian.bitbucket.scm.CommandErrorHandler;
import com.atlassian.bitbucket.scm.CommandOutputHandler;
import com.atlassian.utils.process.ProcessException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Handles copying output from the forked process to the the remote client.
 */
public class SshOutputHandler
        extends AbstractSshStreamHandler
        implements CommandErrorHandler, CommandOutputHandler<Void> {

    private final int bufferSize;
    private final OutputStream outputStream;

    public SshOutputHandler(int bufferSize, OutputStream outputStream) {
        this.bufferSize = bufferSize;
        this.outputStream = checkNotNull(outputStream, "outputStream");
    }

    @Override
    public Void getOutput() {
        return null;
    }

    @Override
    public void process(InputStream inputStream) throws ProcessException {
        try {
            copyStream(inputStream, outputStream, bufferSize);
        } catch (IOException e) {
            throw new ProcessException("Failed to copy stream from forked process to SSH client", e);
        }
    }
}
