package com.pinterest.rocksplicator.monitoring.mbeans;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

public class RocksplicatorMonitor {

  private Logger LOG = LoggerFactory.getLogger(RocksplicatorMonitor.class);

  public static final String ROCKSPLICATOR_REPORT_DOMAIN = "RocksplicatorReport";
  public static final String CLUSTER_DN_KEY = "cluster";
  public static final String INSTANCE_DN_KEY = "instanceName";

  private MBeanServer beanServer;
  private RocksplicatorSpectatorMonitor statsMonitor;
  private String cluster;

  public RocksplicatorMonitor(String clusterName, String instanceName) {
    beanServer = ManagementFactory.getPlatformMBeanServer();
    cluster = clusterName;

    try {
      statsMonitor = new RocksplicatorSpectatorMonitor(instanceName);

      register(statsMonitor, getObjectName(getInstanceBeanName(instanceName)));
    } catch (Exception e) {
      LOG.warn(e.toString());
      e.printStackTrace();
      beanServer = null;
    }
  }

  public void incrementConfigGeneratorCalledCount() {
    statsMonitor.incrementConfigGeneratorCalledCount(1);
  }

  public void incrementConfigGeneratorNullExternalView() {
    statsMonitor.incrementConfigGeneratorNullExternalView(1);
  }

  public void reportConfigGeneratorLatency(double latency) {
    statsMonitor.addLatency(RocksplicatorSpectatorMonitor.LATENCY_TYPE.CONFIG_GENERATOR_EXECUTION, latency);
  }

  private ObjectName getObjectName(String name) throws MalformedObjectNameException {
    LOG.info("Registering bean: " + name);
    return new ObjectName(String.format("%s:%s", ROCKSPLICATOR_REPORT_DOMAIN, name));
  }

  public String clusterBeanName() {
    return String.format("%s=%s", CLUSTER_DN_KEY, cluster);
  }

  private String getInstanceBeanName(String instanceName) {
    return String.format("%s,%s=%s", clusterBeanName(), INSTANCE_DN_KEY, instanceName);
  }

  private void register(Object bean, ObjectName name) {
    if (beanServer == null) {
      LOG.warn("bean server is null, skip reporting");
      return;
    }
    try {
      beanServer.unregisterMBean(name);
    } catch (Exception e1) {
      // Swallow silently
    }

    try {
      beanServer.registerMBean(bean, name);
    } catch (Exception e) {
      LOG.warn("Could not register MBean", e);
    }
  }

}

@@ -674,16 +674,25 @@
 onitor s
+pectatorS
 tatsMoni
@@ -898,24 +898,33 @@
 ry %7B%0A      s
+pectatorS
 tatsMonitor 
@@ -991,16 +991,25 @@
 gister(s
+pectatorS
 tatsMoni
@@ -1236,32 +1236,41 @@
 dCount() %7B%0A    s
+pectatorS
 tatsMonitor.incr
@@ -1366,32 +1366,41 @@
 alView() %7B%0A    s
+pectatorS
 tatsMonitor.incr
@@ -1511,16 +1511,25 @@
  %7B%0A    s
+pectatorS
 tatsMoni
@@ -1531,16 +1531,25 @@
 sMonitor
+%0A        
 .addLate

rename to spectatorStatsMonitor