package com.atlassian.bitbucket.mesh.git.exception;

import com.atlassian.bitbucket.mesh.process.ProcessSummary;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcFailedCommand;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcGitError;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import static java.util.Objects.requireNonNull;

public class CommandFailedException extends AbstractGitException {

    private final String commandLine;
    private final int exitCode;
    private final String stderr;

    public CommandFailedException(@Nullable String message, @Nonnull ProcessSummary summary) {
        this(message, null, summary);
    }

    public CommandFailedException(@Nullable String message, @Nullable Throwable cause,
                                  @Nonnull ProcessSummary summary) {
        super(message, cause, Status.INTERNAL);

        commandLine = requireNonNull(summary, "summary").getCommandLine();
        exitCode = summary.getExitCode();
        stderr = summary.getStderr();
    }

    @Nonnull
    public String getCommandLine() {
        return commandLine;
    }

    public int getExitCode() {
        return exitCode;
    }

    @Nullable
    public String getStderr() {
        return stderr;
    }

    @Nonnull
    @Override
    public RpcGitError toError() {
        return RpcGitError.newBuilder()
                .setFailedCommand(RpcFailedCommand.newBuilder()
                        .setCommandLine(ByteString.copyFromUtf8(commandLine))
                        .setExitCode(exitCode)
                        .setStderr(StringUtils.defaultString(stderr)))
                .build();
    }
}
