package com.atlassian.bitbucket.mesh.git;

import com.atlassian.bitbucket.mesh.git.hook.GitHookService;
import com.atlassian.bitbucket.mesh.process.OsProcess;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcHostingOperationType;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcHostingReadStreamFragment;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcStreamChunk;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcStreamStart;
import com.google.protobuf.ByteString;

import javax.annotation.Nonnull;

public abstract class AbstractHostingReadFragmentHandler<ReqT> extends AbstractHostingFragmentHandler<ReqT, RpcHostingReadStreamFragment> {

    protected AbstractHostingReadFragmentHandler(@Nonnull RpcHostingOperationType defaultOperationType,
                                                 @Nonnull GitHookService hookService) {
        super(defaultOperationType, hookService);
    }

    protected AbstractHostingReadFragmentHandler(@Nonnull RpcHostingOperationType defaultOperationType) {
        super(defaultOperationType);
    }

    @Nonnull
    @Override
    public RpcHostingReadStreamFragment createResultFragment(int exitCode) {
        return RpcHostingReadStreamFragment.newBuilder()
                .setResult(getResult(exitCode))
                .build();
    }

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

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

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