package com.example.struts2.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.ActionContext;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 拦截器状态监控 - 演示拦截器生命周期
 */
public class MonitorInterceptor implements Interceptor {
    
    private static final Map<String, Long> actionCallCounts = new ConcurrentHashMap<>();
    private static long interceptorInitTime;
    
    @Override
    public void init() {
        interceptorInitTime = System.currentTimeMillis();
        System.out.println("[MonitorInterceptor] 初始化 - " + new java.util.Date());
    }
    
    @Override
    public void destroy() {
        System.out.println("[MonitorInterceptor] 销毁 - " + new java.util.Date());
        System.out.println("[MonitorInterceptor] 最终统计: " + actionCallCounts);
    }
    
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        String actionName = invocation.getProxy().getActionName();
        actionCallCounts.merge(actionName, 1L, Long::sum);
        
        // 通过 invocation 获取 context
        ActionContext context = invocation.getInvocationContext();
        Map<String, Object> request = (Map<String, Object>) context.get("request");
        if (request != null) {
            request.put("interceptorInitTime", interceptorInitTime);
            request.put("actionCallCounts", new ConcurrentHashMap<>(actionCallCounts));
        }
        
        return invocation.invoke();
    }
    
    public static Map<String, Long> getStats() {
        return new ConcurrentHashMap<>(actionCallCounts);
    }
}