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

import com.atlassian.bitbucket.mesh.process.ProcessStdioHandler;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.nio.ByteBuffer;
import java.util.function.Supplier;

import static java.util.Objects.requireNonNull;

/**
 * A handler that skips all of the output of the process.
 *
 * @param <T> the type returned by {@link #getResult()}
 */
public class NullStdioHandler<T> implements ProcessStdioHandler<T> {

    private final Supplier<T> getResult;

    public NullStdioHandler() {
        this(() -> null);
    }

    public NullStdioHandler(@Nonnull Supplier<T> getResult) {
        this.getResult = requireNonNull(getResult, "getResult");
    }

    @Nullable
    @Override
    public T getResult() {
        return getResult.get();
    }

    @Override
    public boolean onStdinReady(@Nonnull ByteBuffer buffer) {
        buffer.flip();
        return false;
    }

    @Override
    public void onStdout(@Nonnull ByteBuffer buffer, boolean closed) {
        //Skip to the end of the buffer
        buffer.position(buffer.position() + buffer.remaining());
    }
}
