package WebSide;

import com.google.gson.JsonElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class WebClient {

    private HttpClient client;

    //static final Logger logger = LoggerFactory.getLogger(WebClient.class);
    public WebClient()
    {
        this.client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build();
    }

    /* send task (post http request) asynchronously */
    public String sendQuery(String url, byte[] queryPayload) throws ExecutionException, InterruptedException {
        CompletableFuture<String> response = new CompletableFuture<>();
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .POST(HttpRequest.BodyPublishers.ofByteArray(queryPayload))
                .build();

        response = client.sendAsync
                        (httpRequest ,
                                HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)).
                thenApply(HttpResponse::body);
        /*response = client.sendAsync
                (httpRequest,
                 HttpResponse.BodyHandlers.
                );*/
        String tem = response.join();
        return tem;
    }

}
