package com.qmth.boot.api.interceptor;

import com.qmth.boot.api.config.ApiConfig;
import com.qmth.boot.api.config.ApiConfigService;
import com.qmth.boot.api.config.ApiProperties;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.api.utils.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;

public abstract class AbstractInterceptor extends HandlerInterceptorAdapter implements ApiConstant {

    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    protected ApiConfig getApiConfig(ApiProperties apiProperties, ApiConfigService apiConfigService,
            HttpServletRequest request, Object handler) {
        ApiConfig apiConfig = RequestUtil.getAttribute(request, ATTRIBUTE_API_CONFIG);
        if (apiConfig == null) {
            if (handler instanceof HandlerMethod) {
                apiConfig = apiConfigService.getApiConfig((HandlerMethod) handler);
            }
            // 容器尚未初始化完成时，按照配置构建以防报错
            if (apiConfig == null) {
                apiConfig = new ApiConfig(apiProperties);
            }
            request.setAttribute(ATTRIBUTE_API_CONFIG, apiConfig);
        }
        return apiConfig;
    }

}
