package com.dxhy.auth.client.interceptor;

import java.io.IOException;

import javax.annotation.Resource;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import com.dxhy.auth.client.config.ServiceAuthConfig;
import com.dxhy.auth.client.configuration.UserAuthConfig;
import com.dxhy.auth.client.jwt.ServiceAuthUtil;
import com.dxhy.common.constant.CommonConstants;
import com.dxhy.common.utils.BaseContextHandler;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 *
 * @author jiaohongyang
 * @date 2019年3月26日 下午5:51:48
 *
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Component
@Slf4j
public class OkHttpTokenInterceptor implements Interceptor {
    @Resource
    @Lazy
    private ServiceAuthUtil serviceAuthUtil;
    @Resource
    @Lazy
    private ServiceAuthConfig serviceAuthConfig;
    @Resource
    @Lazy
    private UserAuthConfig userAuthConfig;

    /**
     *
     * @param chain
     *            值
     * @return 返回
     * @throws IOException
     *             异常
     */
    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request newRequest;
        if (chain.request().url().toString().contains("client/token")) {
            newRequest = chain.request().newBuilder()
                .header(userAuthConfig.getTokenHeader(), BaseContextHandler.getToken()).build();
        } else {
            newRequest =
                chain.request().newBuilder().header(userAuthConfig.getTokenHeader(), BaseContextHandler.getToken())
                    .header(serviceAuthConfig.getTokenHeader(), serviceAuthUtil.getClientToken()).build();
        }
        Response response = chain.proceed(newRequest);
        if (HttpStatus.FORBIDDEN.value() == response.code()) {
            if (response.body().toString().contains(String.valueOf(CommonConstants.EX_CLIENT_INVALID_CODE))) {
                log.info("Client Token Expire,Retry to request...");
                serviceAuthUtil.refreshClientToken();
                newRequest =
                    chain.request().newBuilder().header(userAuthConfig.getTokenHeader(), BaseContextHandler.getToken())
                        .header(serviceAuthConfig.getTokenHeader(), serviceAuthUtil.getClientToken()).build();
                response = chain.proceed(newRequest);
            }
        }
        return response;
    }
}
