import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.SocketAddress;
import io.vertx.ext.web.client.WebClient;

public class TrashMigrator {
    final private static int PORT_TDG = 8181;
    final private static int PORT_MY = 8080;
    final private static String HOST = "localhost";
    final private static String TOKEN = "9f226286-e0d8-4125-ad43-b123b4e464da";
    final private static String TYPE = "application/json;charset=utf-8";

    public void get(WebClient client) {
        client
                .post(PORT_TDG, HOST, "/graphql")
                .putHeader("Content-Type", "application/json")
                .sendJsonObject(
                        new JsonObject()
                                .put("query", "{Book { uuid, book_name, author }}")
                )
                .onSuccess(res -> {
                    if (res.statusCode() == 200 &&
                            res.getHeader("content-type").equals(TYPE)) {
                        JsonObject body = res.bodyAsJsonObject();
                        body.stream();
                        post(client, body);
                    }
                });
    }

    public void post(WebClient client, JsonObject body) {
        client
                .post(PORT_TDG, HOST, "/http")
                .putHeader("Content-Type", TYPE)
                .putHeader("auth-token", TOKEN)
                .sendJsonObject(body)
                .onSuccess(res -> {
                    //todo
                });
    }

    public void run(HttpServer server, WebClient client) {
        server.requestHandler(request -> {
            HttpServerResponse response = request.response();
            get(client);
        });
        server.listen(SocketAddress.domainSocketAddress(String.format("%s/%s//api/migrate/graphql", HOST, PORT_MY)));
    }

    public static void main(String[] args) throws Exception {
        Vertx vertx = Vertx.vertx();
        WebClient client = WebClient.create(vertx);
        TrashMigrator migrator = new TrashMigrator();
        HttpServer server = vertx.createHttpServer();
        migrator.run(server, client);
    }
}
