package com.atlassian.bitbucket.mesh.rpc.v1;

import com.google.protobuf.InvalidProtocolBufferException;
import io.grpc.Metadata;
import io.grpc.Status;
import org.slf4j.LoggerFactory;

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

import static java.util.Objects.requireNonNull;

/**
 * Provides some standard utilities to simplify interacting with {@link RpcGitError}s.
 */
public class RpcGitErrorUtils {

    private static final Metadata.Key<RpcGitError> KEY_ERROR = Metadata.Key.of(
            "mesh-git-error-bin", new Metadata.BinaryMarshaller<RpcGitError>() {

                @Override
                public RpcGitError parseBytes(byte[] serialized) {
                    try {
                        return RpcGitError.parseFrom(serialized);
                    } catch (InvalidProtocolBufferException e) {
                        LoggerFactory.getLogger(RpcGitErrorUtils.class)
                                .warn("Failed to parse RpcGitError from trailer", e);
                        return null;
                    }
                }

                @Override
                public byte[] toBytes(RpcGitError value) {
                    return value.toByteArray();
                }
            });

    private RpcGitErrorUtils() {
        throw new UnsupportedOperationException(getClass().getSimpleName() +
                " is a utility class and should not be instantiated");
    }

    /**
     * Parses an {@link RpcGitError} from the provided {@link Metadata}, if one is present <i>and can be parsed
     * successfully</i>.
     *
     * @param metadata the metadata to parse a {@link RpcGitError} from
     * @return the parsed {@link RpcGitError}, or {@code null} if no error was included in the provided metadata
     *         or the error could not be parsed
     */
    @Nullable
    public static RpcGitError fromMetadata(@Nonnull Metadata metadata) {
        return requireNonNull(metadata, "metadata").get(KEY_ERROR);
    }

    /**
     * Parses an {@link RpcGitError} from the provided {@code Throwable}, if it has gRPC {@link Metadata} attached.
     *
     * @param t the exception to parse an {@link RpcGitError} from
     * @return the parsed {@link RpcGitError}, or {@code null} if the exception has no metadata, the metadata has
     *         no included error, or the included error could not be parsed
     */
    @Nullable
    public static RpcGitError fromThrowable(@Nonnull Throwable t) {
        Metadata metadata = Status.trailersFromThrowable(t);

        return metadata == null ? null : fromMetadata(metadata);
    }

    /**
     * Serializes the provided {@link RpcGitError} and returns gRPC {@link Metadata} with a key containing the
     * serialized bytes.
     *
     * @param error the error to serialize
     * @return metadata containing the provided error
     */
    @Nonnull
    public static Metadata toMetadata(@Nonnull RpcGitError error) {
        requireNonNull(error, "error");

        Metadata metadata = new Metadata();
        metadata.put(KEY_ERROR, error);

        return metadata;
    }
}