package com.atlassian.bitbucket.mesh.request;

import com.google.protobuf.MessageLite;
import io.grpc.ForwardingServerCall;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.Status;

/**
 * Wraps a {@link ServerCall} to track the number and size of messages sent, as well as the {@link Status} sent
 * when the call is {@link #close closed}.
 *
 * @param <ReqT>  the request type
 * @param <RespT> the response type
 */
class RequestServerCall<ReqT, RespT> extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {

    private final GrpcRequestDescriptor descriptor;

    RequestServerCall(ServerCall<ReqT, RespT> delegate, GrpcRequestDescriptor descriptor) {
        super(delegate);

        this.descriptor = descriptor;
    }

    @Override
    public void close(Status status, Metadata trailers) {
        descriptor.onClose(status);

        super.close(status, trailers);
    }

    @Override
    public void sendMessage(RespT message) {
        descriptor.onMessageSent();
        if (message instanceof MessageLite) {
            descriptor.onBytesSent(((MessageLite) message).getSerializedSize());
        }

        super.sendMessage(message);
    }
}
