package se.arbetsformedlingen.venice.probe;

import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CheckProbe implements java.util.function.Supplier<ProbeResponse> {
    private final Host host;
    private final Application application;

    private Map<Application, String> ports = new HashMap<>();
    private Map<Application, String> probeNames = new HashMap<>();

    CheckProbe(Host host, Application application) {
        this.host = host;
        this.application = application;

        addPorts();
        addProbeNames();
    }

    private void addPorts() {
        ports.put(new Application("gfr"), "/wildfly05");
    }

    private void addProbeNames() {
        probeNames.put(new Application("gfr"), "UgkForetagProbe");
    }

    @Override
    public ProbeResponse get() {
        String uri = getUri();
        Executor executor = getAuthenticatedExecutor();

        String result;
        try {
            result = executor.execute(Request.Get(uri))
                    .returnContent()
                    .asString();
        } catch (IOException e) {
            throw new CheckProbeException(e.getMessage(), e);
        }

        return ProbeResponseParser.parse(result);
    }

    private String getUri() {
        String hostName = host.getName();
        String port = ports.get(application);
        String ugkForetagProbe = probeNames.get(application);

        return "http://" + hostName + port + "/jolokia/read/af-probe:probe=" + ugkForetagProbe + "/";
    }

    private Executor getAuthenticatedExecutor() {
        String user = System.getenv("PROBE_USER");
        String password = System.getenv("PROBE_PASSWORD");

        return Executor.newInstance()
                .auth(user, password);
    }
}

@@ -136,36 +136,8 @@
 t;%0A%0A
-import java.io.IOException;%0A
 impo
@@ -1137,24 +1137,29 @@
 ring();%0A
+%0A    
         
 %7D catch 
@@ -1154,135 +1154,114 @@
     
-%7D catch (IOException e) %7B%0A            throw new CheckProbeException(e.getMessage(), e);%0A        %7D%0A%0A
+return ProbeResponseParser.parse(result);%0A        %7D catch (Exception e) %7B%0A     
        
- 
 return 
-Probe
+error
 Response
 Pars
@@ -1256,37 +1256,30 @@
 Response
-Parser.parse(result);
+(e);%0A        %7D
 %0A    %7D%0A%0A
@@ -1811,11 +1811,245 @@
 );%0A    %7D
+%0A%0A    private ProbeResponse errorResponse(Exception e) %7B%0A        Status status = new Status(e.getMessage());%0A        Version version = new Version(%22Unknown%22);%0A        return new ProbeResponse(application, host, status, version);%0A    %7D
 %0A%7D%0A

Return an error response if something fails when checking a probe