package com.example.struts2.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.ActionContext;
import java.util.Map;

/**
 * 计时拦截器 - 演示拦截器统计功能
 * 
 * 学习点：
 * - 拦截器状态保持
 * - ActionContext 获取上下文
 * - 多个拦截器协作
 */
public class TimingInterceptor extends AbstractInterceptor {
    
    // 统计数据
    private long totalRequests = 0;
    private long totalTime = 0;
    
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        totalRequests++;
        
        String actionName = invocation.getProxy().getActionName();
        long startTime = System.nanoTime();
        
        // 执行 Action
        String result = invocation.invoke();
        
        long duration = System.nanoTime() - startTime;
        totalTime += duration;
        
        // 存储到 request 作用域
        Map<String, Object> request = (Map<String, Object>) 
            ActionContext.getContext().get("request");
        if (request != null) {
            request.put("executionTimeNs", duration);
            request.put("totalRequests", totalRequests);
        }
        
        System.out.println("[TimingInterceptor] " + actionName + 
            " 执行时间: " + (duration / 1_000_000.0) + " ms");
        
        return result;
    }
    
    public long getTotalRequests() { return totalRequests; }
    public long getTotalTime() { return totalTime; }
}