package com.google.research.bleth.servlets;

import com.google.cloud.tasks.v2.AppEngineHttpRequest;
import com.google.cloud.tasks.v2.CloudTasksClient;
import com.google.cloud.tasks.v2.HttpMethod;
import com.google.cloud.tasks.v2.QueueName;
import com.google.cloud.tasks.v2.Task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/enqueue-simulation")
public class EnqueueSimulationServlet extends HttpServlet {

    static final String projectId = "bleth-2020";
    static final String locationId = "europe-west1";
    static final String queueId = "simulations-queue";

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

        try (CloudTasksClient client = CloudTasksClient.create()) {
            // Construct the fully qualified queue name.
            String queueName = QueueName.of(projectId, locationId, queueId).toString();

            // Construct the task body.
            Task task =
                    Task.newBuilder()
                            .setAppEngineHttpRequest(
                                    AppEngineHttpRequest.newBuilder()
                                            .setRelativeUri("/new-simulation?" + toQueryString(request))
                                            .setHttpMethod(HttpMethod.POST)
                                            .build())
                            .build();

            // Add the task to the queue.
            client.createTask(queueName, task);
        }

        response.setContentType("text/html;");
        response.getWriter().println("Task has been added to queue.");
    }

    private String toQueryString(HttpServletRequest request) {
        List<String> keyValuePairs = new ArrayList<>();
        for (String param : request.getParameterMap().keySet()) {
            keyValuePairs.add(param + "=" + request.getParameter(param));
        }
        return String.join("&", keyValuePairs);
    }
}
@@ -1134,170 +1134,83 @@
 the 
-task body.%0A            Task task =%0A                    Task.newBuilder()%0A                            .setAppEngineHttpRequest(%0A                                   
+HTTP request (for the task).%0A            AppEngineHttpRequest httpRequest =
  App
@@ -1264,32 +1264,8 @@
     
-       
-                 
 .set
@@ -1325,32 +1325,8 @@
 t))%0A
-                        
     
@@ -1385,32 +1385,43 @@
                 
+.build();%0A%0A
                 
@@ -1416,36 +1416,84 @@
         
-            .b
+// Construct the task body.%0A            Task task = Task.newB
 uild
+er
 (
-)
 )%0A      
@@ -1486,32 +1486,82 @@
 ilder()%0A        
+            .setAppEngineHttpRequest(httpRequest)%0A
                 

rearrange servlet code.