package io.galeb.router.configurations;

import io.galeb.router.completionListeners.AccessLogCompletionListener;
import io.galeb.router.completionListeners.StatsdCompletionListener;
import io.galeb.router.handlers.RootHandler;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.NameVirtualHostHandler;
import io.undertow.util.Headers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RootHandlerConfiguration {

    private final NameVirtualHostHandler nameVirtualHostHandler;
    private final AccessLogCompletionListener accessLogCompletionListener;
    private final StatsdCompletionListener statsdCompletionListener;

    @Autowired
    public RootHandlerConfiguration(final NameVirtualHostHandler nameVirtualHostHandler,
                                    final AccessLogCompletionListener accessLogCompletionListener,
                                    final StatsdCompletionListener statsdCompletionListener) {
        this.nameVirtualHostHandler = nameVirtualHostHandler;
        this.accessLogCompletionListener = accessLogCompletionListener;
        this.statsdCompletionListener = statsdCompletionListener;
        nameVirtualHostHandler.addHost("__ping__", pingHandler());
    }

    private HttpHandler pingHandler() {
        return exchange -> {
            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
            exchange.getResponseHeaders().put(Headers.SERVER, "GALEB");
            exchange.getResponseSender().send("WORKING");
        };
    }

    @Bean
    public RootHandler rootHandler() {
        return new RootHandler(nameVirtualHostHandler, accessLogCompletionListener, statsdCompletionListener);
    }

}

@@ -212,32 +212,78 @@
 rs.RootHandler;%0A
+import io.galeb.router.services.ExternalData;%0A
 import io.undert
@@ -297,32 +297,32 @@
 er.HttpHandler;%0A
-
 import io.undert
@@ -838,16 +838,53 @@
 istener;
+%0A    private final ExternalData data;
 %0A%0A    @A
@@ -1171,16 +1171,85 @@
 Listener
+,%0A                                    final ExternalData externalData
 ) %7B%0A    
@@ -1436,32 +1436,61 @@
 letionListener;%0A
+        data = externalData;%0A
         nameVirt
@@ -1821,17 +1821,109 @@
 end(
-%22WORKING%22
+(data.exist(ExternalData.PREFIX_KEY) ? %22WORKING%22 : %22FAIL: %22 + ExternalData.PREFIX_KEY + %22 not found%22)
 );%0A 

define dynamically healthcheck response