package com.atlassian.bitbucket.mesh.process.handler;

import javax.annotation.Nonnull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;

public class BufferStdioHandler extends AbstractProcessStdioHandler<byte[]> {

    private final ByteArrayOutputStream bytes;

    private WritableByteChannel channel;

    public BufferStdioHandler() {
        bytes = new ByteArrayOutputStream();
    }

    @Override
    public byte[] getResult() {
        return bytes.toByteArray();
    }

    @Override
    public void onStdout(@Nonnull ByteBuffer buffer, boolean closed) {
        if (channel == null) {
            if (closed) {
                return;
            }
            channel = Channels.newChannel(bytes);
        }

        try {
            channel.write(buffer);

            if (closed) {
                channel.close();
                channel = null;
            }
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to copy stdout bytes", e);
        }
    }
}
