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;

/**
 * A servlet used for enqueuing a task targeted at endpoint '/new-simulation',
 * in order to create and run a new simulation.
 */
@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 HTTP request (for the task).
            AppEngineHttpRequest httpRequest = AppEngineHttpRequest.newBuilder()
                    .setRelativeUri("/new-simulation?" + toQueryString(request))
                    .setHttpMethod(HttpMethod.POST)
                    .build();

            // Construct the task body.
            Task task = Task.newBuilder()
                    .setAppEngineHttpRequest(httpRequest)
                    .build();

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

        response.setContentType("text/plain;");
        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);
    }
}
@@ -784,25 +784,26 @@
  String 
-projectId
+PROJECT_ID
  = %22blet
@@ -835,26 +835,27 @@
  String 
-locationId
+LOCATION_ID
  = %22euro
@@ -889,23 +889,24 @@
  String 
-queueId
+QUEUE_ID
  = %22simu
@@ -920,16 +920,113 @@
 -queue%22;
+%0A    static final String QUEUE_NAME = QueueName.of(PROJECT_ID, LOCATION_ID, QUEUE_ID).toString();
 %0A%0A    pu
@@ -1194,154 +1194,8 @@
 ) %7B%0A
-            // Construct the fully qualified queue name.%0A            String queueName = QueueName.of(projectId, locationId, queueId).toString();%0A%0A
     
@@ -1740,17 +1740,18 @@
 ask(
-queueName
+QUEUE_NAME
 , ta

change queue name into a class-wide constant.