package ru.yandex.wmconsole.common.metrics;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.graphite.Graphite;
import com.codahale.metrics.graphite.GraphiteReporter;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

/**
 * @author aherman
 */
public class GraphiteMetricsConfigurer {
    private static final Logger log = LoggerFactory.getLogger(GraphiteMetricsConfigurer.class);

    private String host;
    private int port = 2003;

    private String servantName;
    private String servantHostname;

    private MetricRegistry metricRegistry;

    public void init() {
        if (StringUtils.isEmpty(host)) {
            log.warn("Graphite host not configured. Graphite monitoring disabled");
        } else {
            Graphite graphite = new Graphite(new InetSocketAddress(host, port));
            GraphiteReporter reporter = GraphiteReporter.forRegistry(metricRegistry)
                    .prefixedWith(servantHostname.replaceAll("\\.", "_") + ".services.wmc." + servantName)
                    .convertRatesTo(TimeUnit.SECONDS)
                    .convertDurationsTo(TimeUnit.MILLISECONDS)
                    .filter(MetricFilter.ALL)
                    .build(graphite);

            reporter.start(1, TimeUnit.MINUTES);
            log.info("Start graphite metrics report");
            log.info("Graphite: " + host + ":" + port);
        }

        // Debug print
//        ConsoleReporter.enable(1, TimeUnit.MINUTES);
    }

    @Required
    public void setHost(String host) {
        this.host = host;
    }

    public void setPort(int port) {
        this.port = port;
    }

    @Required
    public void setServantName(String servantName) {
        this.servantName = servantName;
    }

    @Required
    public void setServantHostname(String servantHostname) {
        this.servantHostname = servantHostname;
    }

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