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

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

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

import static com.atlassian.bitbucket.mesh.rpc.util.ByteStringUtils.nullToEmpty;
import static java.util.Objects.requireNonNull;

public class RefNameConflictException extends AbstractGitException {

    private final String conflictName;
    private final String refName;

    public RefNameConflictException(@Nonnull String refName) {
        this(refName, null);
    }

    public RefNameConflictException(@Nonnull String refName, @Nullable String conflictName) {
        super("Conflicting ref names: " + refName + " vs " + conflictName, Status.INVALID_ARGUMENT);

        this.conflictName = conflictName;
        this.refName = requireNonNull(refName, "refName");
    }

    @Nullable
    public String getConflictName() {
        return conflictName;
    }

    @Nonnull
    public String getRefName() {
        return refName;
    }

    @Nonnull
    @Override
    public RpcGitError toError() {
        return RpcGitError.newBuilder()
                .setRefNameConflict(RpcRefNameConflict.newBuilder()
                        .setConflictName(nullToEmpty(conflictName))
                        .setRefName(ByteString.copyFromUtf8(refName)))
                .build();
    }
}
