package org.mapfish.print.metrics;

import com.codahale.metrics.MetricRegistry;
import com.readytalk.metrics.StatsDReporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * Will start a StatsD reporter if configured.
 * Using those environment variables or Java system properties:
 * - STATSD_ADDRESS: the address:port of the statsd daemon (if not set, the feature is disabled)
 * - STATSD_PREFIX: the prefix to set (defaults to mapfish-print)
 * - STATSD_PERIOD: the reporting period in seconds (defaults to 10)
 */
public class StatsDReporterInit {
    private static final String ADDRESS = "STATSD_ADDRESS";
    private static final String PREFIX = "STATSD_PREFIX";
    private static final String PERIOD = "STATSD_PERIOD";
    private static final Logger LOGGER = LoggerFactory.getLogger(StatsDReporterInit.class);

    @Autowired
    private MetricRegistry metricRegistry;

    private StatsDReporter reporter = null;

    private String getConfig(final String name, final String def) {
        final String result = System.getenv(name);
        if (result == null) {
            return System.getProperty(name, def);
        }
        return result;
    }

    /**
     * Start the StatsD reporter, if configured.
     * @throws URISyntaxException
     */
    @PostConstruct
    public final void init() throws URISyntaxException {
        final String address = getConfig(ADDRESS, null);
        if (address != null) {
            final URI uri = new URI("udp://" + address);
            final String prefix = getConfig(PREFIX, "mapfish-print");
            final int period = Integer.parseInt(getConfig(PERIOD, "10"));
            LOGGER.info("Starting a StatsD reporter targeting {} with prefix {} and period {}s",
                    uri, prefix, period);
            this.reporter = StatsDReporter.forRegistry(this.metricRegistry)
                    .prefixedWith(prefix)
                    .build(uri.getHost(), uri.getPort());
            this.reporter.start(period, TimeUnit.SECONDS);
        }
    }

    /**
     * Stop the StatsD reporter, if configured.
     */
    @PreDestroy
    public final void shutdown() {
        if (this.reporter != null) {
            LOGGER.info("Stopping the StatsD reporter");
            this.reporter.stop();
        }
    }
}

@@ -239,16 +239,45 @@
 wired;%0A%0A
+import java.net.InetAddress;%0A
 import j
@@ -289,16 +289,16 @@
 et.URI;%0A
-
 import j
@@ -325,16 +325,54 @@
 eption;%0A
+import java.net.UnknownHostException;%0A
 import j
@@ -754,16 +754,52 @@
 h-print)
+. Can use %25h to insert the hostname.
 %0A * - ST
@@ -1898,16 +1898,45 @@
 -print%22)
+.replace(%22%25h%22, getHostname())
 ;%0A      
@@ -2377,16 +2377,16 @@
 CONDS);%0A
-
         
@@ -2386,32 +2386,592 @@
        %7D%0A    %7D%0A%0A
+    private static String getHostname() %7B%0A        String hostname = System.getenv(%22HOSTNAME%22);  // should work on Unix%0A        if (hostname == null) %7B%0A            hostname = System.getenv(%22COMPUTERNAME%22);  // should work on Windows%0A        %7D%0A        if (hostname == null) %7B%0A            try %7B%0A                // last resort%0A                hostname = InetAddress.getLocalHost().getHostName();%0A            %7D catch (UnknownHostException e) %7B%0A                hostname = %22unknown%22;  // fallback%0A            %7D%0A        %7D%0A        return hostname.toLowerCase();%0A    %7D%0A%0A
     /**%0A     * S

Allow to add the hostname into the statsd metrics