package org.atlasapi.system;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.metabroadcast.common.properties.Configurer;

import com.codahale.metrics.Clock;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.MetricSet;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.codahale.metrics.graphite.GraphiteUDP;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.codahale.metrics.jvm.ThreadStatesGaugeSet;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ProcessingMetricsModule extends MetricsModule {

    private final String environmentPrefix = Configurer.get("metrics.environment.prefix").get();
    private final String graphiteHost = Configurer.get("metrics.graphite.host").get();
    private final int graphitePort = Configurer.get("metrics.graphite.port").toInt();

    @Override
    public MetricRegistry metrics() {
        MetricRegistry metrics = new MetricRegistry();
        registerMetrics("gc.", new GarbageCollectorMetricSet(), metrics);
        registerMetrics("memory.", new MemoryUsageGaugeSet(), metrics);
        registerMetrics("threads.", new ThreadStatesGaugeSet(), metrics);
        graphiteReporterFor(metrics);
        return metrics;
    }

    private void registerMetrics(String prefix, MetricSet metrics, MetricRegistry registry) {
        for (Map.Entry<String, Metric> metric : metrics.getMetrics().entrySet()) {
            registry.register(prefix.concat(metric.getKey()), metric.getValue());
        }
    }

    private GraphiteReporter graphiteReporterFor(MetricRegistry metrics) {
        GraphiteReporter reporter = GraphiteReporter.forRegistry(metrics)
                .prefixedWith("atlas.deer." + environmentPrefix + ".")
                .withClock(new Clock.UserTimeClock())
                .build(new GraphiteUDP(graphiteHost, graphitePort));
        reporter.start(1, TimeUnit.MINUTES);
        return reporter;
    }
}

@@ -339,24 +339,16 @@
 Graphite
-Reporter
 ;%0Aimport
@@ -386,19 +386,24 @@
 Graphite
-UDP
+Reporter
 ;%0Aimport
@@ -1075,24 +1075,25 @@
 Registry();%0A
+%0A
         regi
@@ -1300,24 +1300,25 @@
 trics);%0A
+%0A
         
 graphite
@@ -1309,17 +1309,22 @@
         
-g
+startG
 raphiteR
@@ -1330,19 +1330,16 @@
 Reporter
-For
 (metrics
@@ -1333,32 +1333,33 @@
 orter(metrics);%0A
+%0A
         return m
@@ -1665,26 +1665,19 @@
 ate 
-GraphiteReporter g
+void startG
 raph
@@ -1691,11 +1691,8 @@
 rter
-For
 (Met
@@ -1952,11 +1952,8 @@
 hite
-UDP
 (gra
@@ -1975,24 +1975,25 @@
 hitePort));%0A
+%0A
         repo
@@ -2029,33 +2029,8 @@
 S);%0A
-        return reporter;%0A
     

Change Graphite reporter to use TCP