package com.yeejoin.equipmanage.remote;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;
import feign.RequestTemplate;

public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {
    public FeignBasicAuthRequestInterceptor() {

    }

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();

            /* Get token from header */
            String authToken = request.getHeader("token");
            /* If token not found get it from request parameter */
            if (StringUtils.isBlank(authToken)) {
                authToken = request.getHeader("X-Access-Token");
            }
            template.header("X-Access-Token", authToken);
            template.header("token", authToken);
            template.header("appKey", request.getHeader("appKey"));
            template.header("product", request.getHeader("product"));
        }
    }
}
