package eu.dnetlib.broker.metrics;

import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.prometheus.client.Counter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class RequestCounterInterceptor extends HandlerInterceptorAdapter implements MetricInterceptor {

	private static final Counter requestTotal = Counter.build()
			.name("http_requests_total")
			.labelNames("method", "handler", "status")
			.help("Http Request Total").register();

	@Override
	public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception e) throws Exception {

		String handlerLabel = handler.toString();
		// get short form of handler method name
		if (handler instanceof HandlerMethod) {
			Method method = ((HandlerMethod) handler).getMethod();
			handlerLabel = method.getDeclaringClass().getSimpleName() + "." + method.getName();
		}
		requestTotal.labels(
				request.getMethod(),
				handlerLabel,
				Integer.toString(response.getStatus())).inc();
	}

}
