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;
import org.typroject.tyboot.core.foundation.context.RequestContext;

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)) {
                if (StringUtils.isBlank(RequestContext.getToken())) {
                    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"));
                    template.header("clientType", "feignClient");
                } else {
                    template.header("X-Access-Token", RequestContext.getToken());
                    System.out.println(RequestContext.getToken());
                    template.header("token", RequestContext.getToken());
                    template.header("appKey", RequestContext.getAppKey());
                    template.header("product", RequestContext.getProduct());
                    template.header("clientType", "feignClient");
                }
            } else {
                template.header("X-Access-Token", authToken);
                template.header("token", authToken);
                template.header("appKey", request.getHeader("appKey"));
                template.header("product", request.getHeader("product"));
                template.header("clientType", "feignClient");
            }
        }
    }
}
