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

import com.atlassian.bitbucket.mesh.process.ProcessSummary;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcCommandTimeout;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcGitError;
import com.google.protobuf.ByteString;
import io.grpc.Status;

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

import static java.util.Objects.requireNonNull;

public class CommandTimeoutException extends AbstractGitException {

    private final String commandLine;
    private final int exitCode;

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

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

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

    public CommandTimeoutException(@Nonnull ProcessSummary summary) {
        this("[" + summary + "] timed out", null, summary);
    }

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

    public int getExitCode() {
        return exitCode;
    }

    @Nonnull
    @Override
    public RpcGitError toError() {
        return RpcGitError.newBuilder()
                .setCommandTimeout(RpcCommandTimeout.newBuilder()
                        .setCommandLine(ByteString.copyFromUtf8(commandLine))
                        .setExitCode(exitCode))
                .build();
    }
}
