package com.atlassian.bitbucket.mesh.auth;

import io.grpc.*;

import java.util.concurrent.Executor;

import static com.atlassian.bitbucket.mesh.rpc.MetadataKeys.KEY_TOKEN;

public class AuthenticationClientInterceptor implements ClientInterceptor {

    private final CallCredentials credentials;

    public AuthenticationClientInterceptor(Authenticator authenticator) {
        credentials = new CallCredentials() {

            @Override
            public void applyRequestMetadata(RequestInfo requestInfo, Executor executor, MetadataApplier applier) {
                String token = authenticator.sign(requestInfo.getMethodDescriptor().getFullMethodName());

                Metadata metadata = new Metadata();
                metadata.put(KEY_TOKEN, token);

                applier.apply(metadata);
            }

            @Override
            public void thisUsesUnstableApi() {
            }
        };
    }

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method,
                                                               CallOptions callOptions, Channel next) {
        return next.newCall(method, callOptions.withCallCredentials(credentials));
    }
}
