package ru.yandex.webmaster.common.http;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.eclipse.jetty.server.Request;
import org.springframework.beans.factory.annotation.Required;
import ru.yandex.wmtools.common.framework.http.HttpRequestHandler;

/**
 * @author aherman
 */
public class MetricsHttpRequestHandler extends HttpRequestHandler {
    private MetricRegistry metricRegistry;

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException
    {
        String servantletName = target;
        if (target.charAt(0) == '/') {
            servantletName = target.substring(1);
        }
        Timer.Context timerContext = null;
        if (!servantletName.isEmpty()) {
            Timer timer = metricRegistry.timer("servantlet." + servantletName + ".time");
            timerContext = timer.time();
        }
        try {
            super.handle(target, baseRequest, request, response);
        } finally {
            if (timerContext != null) {
                timerContext.stop();
            }
        }
    }

    @Required
    public void setMetricRegistry(MetricRegistry metricRegistry) {
        this.metricRegistry = metricRegistry;
    }
}
