package com.atlassian.bitbucket.mesh.git;

import com.atlassian.bitbucket.mesh.process.OsProcess;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcStreamChunk;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcStreamFragment;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcStreamResult;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcStreamStart;
import com.google.protobuf.ByteString;

import javax.annotation.Nonnull;

public class RpcStreamFragmentFactory implements RpcResponseFragmentFactory<RpcStreamFragment> {

    public static final RpcStreamFragmentFactory INSTANCE = new RpcStreamFragmentFactory();

    @Nonnull
    @Override
    public RpcStreamFragment createResultFragment(int exitCode) {
        return RpcStreamFragment.newBuilder()
                .setResult(RpcStreamResult.newBuilder()
                        .setExitCode(exitCode)
                        .build())
                .build();
    }

    @Nonnull
    @Override
    public RpcStreamFragment createStartFragment(@Nonnull OsProcess process) {
        return RpcStreamFragment.newBuilder()
                .setStart(RpcStreamStart.newBuilder()
                        .setCommandLine(ByteString.copyFromUtf8(process.toString()))
                        .build())
                .build();
    }

    @Nonnull
    @Override
    public RpcStreamFragment createStderrFragment(@Nonnull RpcStreamChunk stderr) {
        return RpcStreamFragment.newBuilder()
                .setStderr(stderr)
                .build();
    }

    @Nonnull
    @Override
    public RpcStreamFragment createStdoutFragment(@Nonnull RpcStreamChunk stdout) {
        return RpcStreamFragment.newBuilder()
                .setStdout(stdout)
                .build();
    }
}
