package com.yeejoin.amos.boot.biz.common.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import javax.servlet.http.HttpServletRequest;

/**
 * @author DELL
 */
public class FeignAuthRequestInterceptor implements RequestInterceptor {
    public FeignAuthRequestInterceptor() {

    }

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            /* Get token from header */
            String authToken = StringUtils.isEmpty(request.getHeader("X-Access-Token")) ? request.getHeader("token") : request.getHeader("X-Access-Token");
            /* If token not found get it from request parameter */
            String appKey =  request.getHeader("appKey");
            String product =  request.getHeader("product");
            if (authToken == null) {
                authToken = request.getParameter("token");
            }
            if (appKey == null) {
                appKey = request.getParameter("appKey");
            }
            if (product == null) {
                product = request.getParameter("product");
            }
            if (authToken == null) {
                authToken = RequestContext.getToken();
            }
            if (appKey == null) {
                appKey = RequestContext.getAppKey();
            }
            if (product == null) {
                product = RequestContext.getProduct();
            }
            template.header("X-Access-Token", authToken);
            template.header("token", authToken);
            template.header("appKey", appKey);
            template.header("product", product);
        } else {
            template.header("X-Access-Token", RequestContext.getToken());
            template.header("token", RequestContext.getToken());
            template.header("appKey", RequestContext.getAppKey());
            template.header("product", RequestContext.getProduct());
        }
    }
}
