package com.atlassian.bitbucket.mesh.git;

import com.atlassian.bitbucket.mesh.process.OsProcess;
import com.atlassian.bitbucket.mesh.process.handler.LineEncoder;
import io.grpc.stub.StreamObserver;

import javax.annotation.Nonnull;
import java.nio.ByteBuffer;
import java.util.List;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;

/**
 * {@link FragmentProcessStdioHandler} specialization that writes a list of lines to stdin
 *
 * @param <T> the fragment type
 */
public class FragmentProcessInputHandler<T> extends FragmentProcessStdioHandler<T> {

    private final LineEncoder stdinEncoder;

    public FragmentProcessInputHandler(@Nonnull StreamObserver<T> observer,
                                       @Nonnull RpcResponseFragmentFactory<T> fragmentFactory,
                                       @Nonnull List<String> lines) {
        super(observer, fragmentFactory);

        stdinEncoder = new LineEncoder(requireNonNull(lines, "lines"), UTF_8);
    }

    @Override
    public void onStart(@Nonnull OsProcess process) {
        super.onStart(process);

        if (stdinEncoder.hasMore()) {
            process.wantWrite();
        } else {
            process.closeStdin(false);
        }
    }

    @Override
    public boolean onStdinReady(@Nonnull ByteBuffer buffer) {
        if (stdinEncoder.encodeTo(buffer)) {
            return true;
        }
        closeStdin();
        return false;
    }
}
