package com.qmth.boot.core.retrofit.interceptor;

import com.qmth.boot.core.retrofit.interfaces.SignatureProvider;
import com.qmth.boot.core.retrofit.utils.SignatureInfo;
import com.qmth.boot.tools.signature.SignatureEntity;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * 签名构造器，符合开发框架通用鉴权标准
 */
public class SignatureInterceptor implements Interceptor {

    private static final String HEADER_KEY_AUTHORIZATION = "authorization";

    private static final String HEADER_KEY_TIME = "time";

    private SignatureProvider provider;

    public SignatureInterceptor(SignatureProvider provider) {
        this.provider = provider;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        SignatureProvider provider = getSignatureInfo(request);
        if (provider == null) {
            provider = this.provider;
        }
        if (provider != null) {
            long time = System.currentTimeMillis();
            String signature = SignatureEntity
                    .build(provider.getType(), request.method(), request.url().uri().getPath(), time,
                            provider.getIdentity(), provider.getSecret());
            return chain.proceed(
                    request.newBuilder().removeHeader(HEADER_KEY_TIME).removeHeader(HEADER_KEY_AUTHORIZATION)
                            .addHeader(HEADER_KEY_TIME, String.valueOf(time))
                            .addHeader(HEADER_KEY_AUTHORIZATION, signature).build());
        } else {
            return chain.proceed(request);
        }
    }

    private SignatureInfo getSignatureInfo(Request request) {
        try {
            return request.tag(SignatureInfo.class);
        } catch (Exception e) {
            return null;
        }
    }

}
