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

import com.atlassian.bitbucket.mesh.rpc.v1.RpcGitError;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcMergeFailed;
import io.grpc.Status;

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

import static io.grpc.Status.FAILED_PRECONDITION;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang3.StringUtils.defaultString;

public class MergeException extends AbstractGitException {

    protected String fromCommitId;

    public MergeException(@Nonnull String message) {
        super(requireNonNull(message, "message"), FAILED_PRECONDITION);
    }

    public MergeException(@Nonnull String message, @Nonnull Status status) {
        super(requireNonNull(message, "message"), status);
    }

    public MergeException(@Nonnull String message, @Nullable Throwable cause) {
        super(requireNonNull(message, "message"), cause, FAILED_PRECONDITION);
    }

    public MergeException(@Nonnull String message, @Nullable Throwable cause, @Nonnull String fromCommitId) {
        super(requireNonNull(message, "message"), cause, FAILED_PRECONDITION);

        this.fromCommitId = requireNonNull(fromCommitId, "fromCommitId");
    }

    public void setFromCommitId(@Nonnull String fromCommitId) {
        this.fromCommitId = requireNonNull(fromCommitId, "fromCommitId");
    }

    @Nonnull
    @Override
    public RpcGitError toError() {
        return RpcGitError.newBuilder()
                .setMergeFailed(RpcMergeFailed.newBuilder()
                        .setFromCommitId(defaultString(fromCommitId)))
                .build();
    }
}
