package com.atlassian.bitbucket.mesh.git.builder.updateref;

import com.atlassian.bitbucket.mesh.process.OsProcess;
import com.atlassian.bitbucket.mesh.process.handler.AbstractLoggingStdioHandler;
import com.atlassian.bitbucket.mesh.process.handler.LineEncoder;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;

public class UpdateRefStdioHandler extends AbstractLoggingStdioHandler<Void> {

    private final LineEncoder stdinEncoder;

    public UpdateRefStdioHandler(@Nonnull Stream<String> instructions, boolean nullTerminated) {
        super(LoggerFactory.getLogger(UpdateRefStdioHandler.class));

        stdinEncoder = new LineEncoder(instructions.iterator(), StandardCharsets.UTF_8,
                nullTerminated ? LineEncoder.Mode.NULL : LineEncoder.Mode.LF);
    }

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

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

        process.wantWrite();
    }

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