package de.is24.util.monitoring;

import de.is24.util.monitoring.jmx.JmxAppMon4JNamingStrategy;
import de.is24.util.monitoring.keyhandler.DefaultKeyEscaper;
import de.is24.util.monitoring.tools.DoNothingReportVisitor;
import org.junit.Before;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;


public class InApplicationMonitorTest {
  private static final String INITIALIZED_COUNTER_1 = "initialized.counter.1";

  @Before
  public void setupClass() {
    InApplicationMonitor.resetInstanceForTesting();
  }

  @Test
  public void explicitInitializationShouldTakeOverInitializedCountersAndTimers() {
    InApplicationMonitor.getInstance().initializeCounter(INITIALIZED_COUNTER_1);


    DefaultKeyEscaper keyEscaper = new DefaultKeyEscaper();
    CorePlugin corePlugin = new CorePlugin(new JmxAppMon4JNamingStrategy() {
        @Override
        public String getJmxPrefix() {
          return "lala";
        }
      }, keyEscaper);
    InApplicationMonitor explicitInitializedInApplicationMonitor = InApplicationMonitor.initInstance(
      corePlugin, keyEscaper);

    CheckForCounterExistenceReportVisitor reportVisitor = new CheckForCounterExistenceReportVisitor(
      INITIALIZED_COUNTER_1);
    explicitInitializedInApplicationMonitor.getCorePlugin().reportInto(reportVisitor);
    assertThat(reportVisitor.found).isTrue();
  }

  private static class CheckForCounterExistenceReportVisitor extends DoNothingReportVisitor {
    private final String counterName;
    private boolean found = false;

    CheckForCounterExistenceReportVisitor(String counterName) {
      this.counterName = counterName;
    }

    @Override
    public void reportCounter(Counter counter) {
      if (counter.getName().equals(counterName)) {
        found = true;
      }
    }

  }
}

@@ -707,17 +707,16 @@
 ER_1);%0A%0A
-%0A
     Defa
@@ -1223,16 +1223,110 @@
 TER_1);%0A
+    assertThat(explicitInitializedInApplicationMonitor.getCorePlugin()).isSameAs(corePlugin);%0A
     expl
@@ -1446,24 +1446,214 @@
 ).isTrue();%0A
+    assertThat(JMXTestHelper.checkInApplicationMonitorJMXBeanRegistered(%22lala%22)).isEqualTo(true);%0A%0A    assertThat(JMXTestHelper.getCounterValue(%22lala%22, INITIALIZED_COUNTER_1)).isEqualTo(0);%0A
   %7D%0A%0A  priva

add test to reproduce missing initialized counters in JMX