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() {
        RequestContext.setAppKey("AMOS_STUDIO");
        RequestContext.setProduct("AMOS_STUDIO_WEB");
        RequestContext.setToken("abac3a97-1fe0-4cf0-88a2-12c9104b1f81");

    }

    @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");
            }
            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());
        }
    }
}
