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

import com.atlassian.bitbucket.mesh.rpc.v1.RpcFailedCommand;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcGitError;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcUnsupportedArgument;
import com.google.protobuf.ByteString;

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

import static com.atlassian.bitbucket.mesh.rpc.v1.RpcUnsupportedArgument.Reason;
import static java.util.Objects.requireNonNull;

public class UnsupportedArgumentException extends AbstractValidationException {

    private final String commandLine;
    private final Reason reason;
    private final String value;

    public UnsupportedArgumentException(@Nonnull Reason reason, @Nonnull Object value) {
        this(reason, value, null);
    }

    public UnsupportedArgumentException(@Nonnull Reason reason, @Nonnull Object value, @Nullable String commandLine) {
        super("Unsupported argument: " + value + " (" + reason + ")");

        this.commandLine = commandLine;
        this.reason = requireNonNull(reason, "reason");
        this.value = requireNonNull(value, "value").toString();
    }

    @Nonnull
    public Reason getReason() {
        return reason;
    }

    @Nonnull
    public String getValue() {
        return value;
    }

    @Nonnull
    @Override
    public RpcGitError toError() {
        RpcGitError.Builder builder = RpcGitError.newBuilder()
                .setUnsupportedArgument(RpcUnsupportedArgument.newBuilder()
                        .setReason(reason)
                        .setValue(ByteString.copyFromUtf8(value)));
        if (commandLine != null) {
            builder.setFailedCommand(RpcFailedCommand.newBuilder()
                    .setCommandLine(ByteString.copyFromUtf8(commandLine))
                    .setExitCode(-1)
                    .setStderr(value));
        }
        return builder.build();
    }
}
