package link.at17.mid.tushare.component;


import lombok.extern.slf4j.Slf4j;

import org.reflections.Reflections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import link.at17.mid.tushare.annotation.StaticAttribute;
import link.at17.mid.tushare.data.models.UpdateMethodInfo;
import link.at17.mid.tushare.service.UpdateMethodService;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * 更新注入拦截器
 * <p>
 * 更新方法参数一般是枚举（目前也仅支持枚举）, 此处便是将这些枚举注入到前端以供使用 
 */
@Component
@Slf4j
public class UpdateMethodInterceptor implements HandlerInterceptor {

    @Autowired
    Reflections reflections;
    
    Map<String, Class<?>> optionArgCache;
    
    @Autowired
    UpdateMethodService updateDataService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        injectNecessary(request, handler);
        return true;
    }
    
    /**
     * 为前端模板注入变量
     * @param request
     */
    public void injectNecessary(HttpServletRequest request, Object handler) {
     
        // 只在 Controller（HandlerMethod）里才做注入
        if (!(handler instanceof HandlerMethod)) {
            // 静态资源、图片、css、js 都会被 ResourceHttpRequestHandler 处理，
            // 这里一律跳过
            return;
        }
        
        // 排除 @ResponseBody/json 接口
        HandlerMethod hm = (HandlerMethod) handler;
        if (hm.hasMethodAnnotation(ResponseBody.class) 
         || hm.getBeanType().isAnnotationPresent(RestController.class)) {
            return;
        }
        
        
        if (optionArgCache == null) {
            
            optionArgCache = new HashMap<>();
            
            // 扫描潜在更新方法, 并读取其参数
            List<UpdateMethodInfo> potentialUpdateMethods = updateDataService.getPotentialUpdateMethodInfos();
            for (UpdateMethodInfo info : potentialUpdateMethods) {
                for (UpdateMethodInfo.UpdateParamInfo paramInfo : info.getParams()) {
                    Class<?> typeClass = paramInfo.getTypeClass();
                    if (typeClass == null) continue;
                    if (typeClass.isEnum()) {
                        StaticAttribute sa = typeClass.getAnnotation(StaticAttribute.class);
                        String simpleNmae = typeClass.getSimpleName();
                        if (sa != null) {
                            log.info("UpdateMethod {} 的参数 {}, 类型 {} 已被 @StaticAttribute 注解，不再重复注入",
                                    info.getMethodName(), paramInfo.getName(), simpleNmae);
                            continue;
                        }
                        if (optionArgCache.containsKey(simpleNmae)) {
                            log.warn("UpdateMethod {} 参数 {}, 类型 {} 指定的名称 {} 已经存在, 旧值会被覆盖",
                                    typeClass,
                                    simpleNmae);
                        }
                        optionArgCache.put(simpleNmae, typeClass);
                        log.debug("{} 类以 {} 为名称注入", typeClass, simpleNmae);
                    }
                }
            }
        }
        else if (optionArgCache.isEmpty()) {
            // 跑完一次后，缓存仍然为空，可能不正常，提示一下
            log.warn("初始化后，Option(s)Arg(s)' 缓存为空，这仅在无任何方法被 UpdateMethod 注解，或 UpdateMethod 不存在枚举类参数的情况下出现。如果这与您的期望不符，请检查");
        }
        Iterator<Map.Entry<String, Class<?>>> iterator = optionArgCache.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Class<?>> entry = iterator.next();
            request.setAttribute(entry.getKey(), entry.getValue());
        }
    }
    
}
