package io.scalecube.gateway;

import io.scalecube.gateway.examples.GreetingService;
import io.scalecube.gateway.examples.GreetingServiceImpl;
import io.scalecube.services.Microservices;
import io.scalecube.transport.Address;

import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MicroservicesExtension implements AfterAllCallback {

  private static final Logger LOGGER = LoggerFactory.getLogger(MicroservicesExtension.class);

  private Microservices gateway;
  private Address gatewayAddress;
  private Microservices services;
  private Address serviceAddress;

  public Microservices getGateway() {
    return gateway;
  }

  public Address getGatewayAddress() {
    return gatewayAddress;
  }

  public Microservices getServices() {
    return services;
  }

  public Address getServiceAddress() {
    return serviceAddress;
  }

  public MicroservicesExtension startGateway() {
    gateway = Microservices.builder().startAwait();
    gatewayAddress = gateway.cluster().address();
    LOGGER.info("Started gateway {} on {}", gateway, gatewayAddress);
    return this;
  }

  public MicroservicesExtension startServices(Address gatewayAddress) {
    return startServices(gatewayAddress, new GreetingServiceImpl());
  }

  public MicroservicesExtension startServices(Address gatewayAddress, GreetingService service) {
    services = Microservices.builder()
        .seeds(gatewayAddress)
        .services(service)
        .startAwait();
    serviceAddress = services.serviceAddress();
    LOGGER.info("Started services {} on {}", services, serviceAddress);
    return this;
  }

  public MicroservicesExtension shutdownGateway() {
    if (gateway != null) {
      try {
        gateway.shutdown();
      } catch (Throwable ignore) {
      }
      LOGGER.info("Shutdown gateway {} on {}", gateway, gatewayAddress);
    }
    return this;
  }

  public MicroservicesExtension shutdownServices() {
    if (services != null) {
      try {
        services.shutdown();
      } catch (Throwable ignore) {
      }
      LOGGER.info("Shutdown services {} on {}", services, serviceAddress);
    }
    return this;
  }

  @Override
  public void afterAll(ExtensionContext context) {
    shutdownGateway();
    shutdownServices();
  }
}

@@ -24,16 +24,101 @@
 teway;%0A%0A
+import com.codahale.metrics.CsvReporter;%0Aimport com.codahale.metrics.MetricRegistry;%0A
 import i
@@ -163,16 +163,16 @@
 ervice;%0A
-
 import i
@@ -477,16 +477,76 @@
 ctory;%0A%0A
+import java.io.File;%0Aimport java.util.concurrent.TimeUnit;%0A%0A
 public c
@@ -604,16 +604,16 @@
 back %7B%0A%0A
-
   privat
@@ -697,16 +697,79 @@
 .class);
+%0A  private static final String REPORTER_PATH = %22metrics/tests%22;
 %0A%0A  priv

add KPI-s to gateway: connections meter, req/resp meters, r… (#87)