package com.redhat.developers.msa.api_gateway;

import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import com.github.kristofa.brave.Brave;
import com.github.kristofa.brave.EmptySpanCollectorMetricsHandler;
import com.github.kristofa.brave.ServerRequestInterceptor;
import com.github.kristofa.brave.ServerResponseInterceptor;
import com.github.kristofa.brave.http.DefaultSpanNameProvider;
import com.github.kristofa.brave.http.HttpSpanCollector;
import com.github.kristofa.brave.servlet.BraveServletFilter;

@Configuration
public class ZipKinConfiguration {

    /**
     * Register the ZipKin Filter to intercept {@link ServerRequestInterceptor} and {@link ServerResponseInterceptor}
     * 
     * @return
     */
    @Bean
    public FilterRegistrationBean zipkinFilter() {
        Brave brave = getBrave();
        FilterRegistrationBean registration =
            new FilterRegistrationBean(new BraveServletFilter(brave.serverRequestInterceptor(), brave.serverResponseInterceptor(), new DefaultSpanNameProvider()));
        // Explicit mapping to avoid trace on readiness probe
        registration.addUrlPatterns("/api");
        return registration;
    }

    /**
     * The instance of {@link Brave} - A instrumentation library for Zipkin
     * 
     * @return
     */
    @Bean
    @Scope(value = "singleton")
    public Brave getBrave() {
        Brave brave = new Brave.Builder("api-gateway")
            .spanCollector(HttpSpanCollector.create(System.getenv("ZIPKIN_SERVER_URL"),
            		new EmptySpanCollectorMetricsHandler()))
            .build();
        return brave;
    }

}

@@ -499,32 +499,80 @@
 nseInterceptor;%0A
+import com.github.kristofa.brave.Brave.Builder;%0A
 import com.githu
@@ -1592,54 +1592,292 @@
     
-Brave brave = new Brave.Builder(%22api-gateway
+String zipkingServer = System.getenv(%22ZIPKIN_SERVER_URL%22);%0A        Builder builder = new Brave.Builder(%22ola%22);%0A        if (null == zipkingServer) %7B%0A            // Default configuration%0A            System.out.println(%22No ZIPKIN_SERVER_URL defined. Printing zipkin traces to console.
 %22)
+;
 %0A   
@@ -1885,16 +1885,128 @@
         
+return builder.build();%0A        %7D else %7B%0A            // Brave configured for a Server%0A            return builder
 .spanCol
@@ -2089,10 +2089,12 @@
     
-%09%09
+    
 new 
@@ -2142,16 +2142,20 @@
         
+    
 .build()
@@ -2168,21 +2168,9 @@
     
-return brave;
+%7D
 %0A   

Allow ZipKin to run locally