package uk.ac.ic.wlgitbridge.io.http.ning;

import io.netty.handler.codec.http.HttpHeaders;
import org.asynchttpclient.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ic.wlgitbridge.util.FunctionT;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class NingHttpClient implements NingHttpClientFacade {

    private static final Logger log
            = LoggerFactory.getLogger(NingHttpClient.class);

    private final AsyncHttpClient http;

    public NingHttpClient(AsyncHttpClient http) {
        this.http = http;
    }

    @Override
    public <E extends Exception> byte[] get(
            String url,
            FunctionT<HttpHeaders, Boolean, E> handler
    ) throws ExecutionException {
        try {
            return http
                    .prepareGet(url)
                    .execute(new AsyncCompletionHandler<byte[]>() {

                ByteArrayOutputStream bytes = new ByteArrayOutputStream();

                @Override
                public State onHeadersReceived(
                        HttpHeaders headers
                ) throws E {
                    return handler.apply(headers)
                            ? State.CONTINUE : State.ABORT;
                }

                @Override
                public State onBodyPartReceived(
                        HttpResponseBodyPart content
                ) throws IOException {
                    bytes.write(content.getBodyPartBytes());
                    return State.CONTINUE;
                }

                @Override
                public byte[] onCompleted(
                        Response response
                ) throws IOException {
                    byte[] ret = bytes.toByteArray();
                    bytes.close();
                    log.info(
                            response.getStatusCode()
                                    + " "
                                    + response.getStatusText()
                                    + " ("
                                    + ret.length
                                    + "B) -> "
                                    + url
                    );
                    return ret;
                }

            }).get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}

@@ -1703,34 +1703,32 @@
        ) throws 
-IO
 Exception %7B%0A    
@@ -1715,32 +1715,300 @@
 ows Exception %7B%0A
+                    int statusCode = response.getStatusCode();%0A                    if (statusCode %3E= 400) %7B%0A                        throw new Exception(%22got status %22 + statusCode +%0A                                            %22 fetching %22 + url);%0A                    %7D%0A
                 
@@ -2138,29 +2138,17 @@
         
-response.getS
+s
 tatusCod
@@ -2148,18 +2148,16 @@
 atusCode
-()
 %0A       

Handle errors from the history service