package io.prometheus.client.vertx;

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Gauge;
import io.prometheus.client.vertx.MetricsHandler;
import io.vertx.core.Vertx;
import io.vertx.ext.web.Router;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.URL;
import java.util.Scanner;

import static org.assertj.core.api.Assertions.assertThat;

public class MetricsHandlerTest {

  private static Vertx vertx;
  private static Integer port;
  private static CollectorRegistry registry;

  @BeforeClass
  public static void setUp() throws IOException {
    vertx = Vertx.vertx();
    final Vertx vertx = Vertx.vertx();
    final Router router = Router.router(vertx);

    registry = new CollectorRegistry();
    router.route("/metrics").handler(new MetricsHandler(registry));

    ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();
    socket.close();
    vertx.createHttpServer().requestHandler(router::accept).listen(port);

    Gauge.build("a", "a help").register(registry);
    Gauge.build("b", "b help").register(registry);
    Gauge.build("c", "c help").register(registry);
  }

  @AfterClass
  public static void tearDown() {
    vertx.close();
  }

  @Test
  public void metricsRequest_shouldReturnMetrics() throws IOException {
    String out = makeRequest("/metrics");

    assertThat(out).contains("a 0.0");
    assertThat(out).contains("b 0.0");
    assertThat(out).contains("c 0.0");
  }

  @Test
  public void metricsRequest_shouldAllowFilteringMetrics() throws IOException {
    String out = makeRequest("/metrics?name[]=b&name[]=c");

    assertThat(out).doesNotContain("a 0.0");
    assertThat(out).contains("b 0.0");
    assertThat(out).contains("c 0.0");
  }


  private String makeRequest(String url) throws IOException {
    Scanner scanner = new Scanner(new URL("http://localhost:" + port + url).openStream(), "UTF-8")
            .useDelimiter("\\A");
    String out = scanner.next();
    scanner.close();
    return out;
  }
}

@@ -116,58 +116,8 @@
 ge;%0A
-import io.prometheus.client.vertx.MetricsHandler;%0A
 impo
@@ -359,16 +359,93 @@
 Scanner;
+%0Aimport java.util.concurrent.Semaphore;%0Aimport java.util.concurrent.TimeUnit;
 %0A%0Aimport
@@ -686,37 +686,73 @@
 Up() throws 
-IOException %7B
+Throwable %7B%0A    Semaphore s = new Semaphore(1);%0A%0A
 %0A    vertx =
@@ -960,24 +960,174 @@
 egistry));%0A%0A
+    router.route(%22/test%22).handler(routingContext -%3E %7B%0A      routingContext.response().putHeader(%22content-type%22, %22text%22).end(%22Hello World!%22);%0A    %7D);%0A%0A
     ServerSo
@@ -1210,24 +1210,42 @@
 ket.close();
+%0A%0A    s.acquire();
 %0A    vertx.c
@@ -1304,16 +1304,96 @@
 ten(port
+,%0A            event -%3E s.release()%0A    );%0A%0A    s.tryAcquire(10, TimeUnit.SECONDS
 );%0A%0A    

check that server is ready