package com.google.sps.servlets;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.Process;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.gson.Gson;

/** Servlet that actions items.*/
@WebServlet("/actions")
public class ActionsServlet extends HttpServlet {

  private static final List<String> terms = Arrays.asList("Black Lives Matter", "COVID-19");
  private static final String API_KEY = "API_KEY";  // Insert the API_KEY here for testing.
  private static final String API_PATH = "https://api.globalgiving.org/api/public/services/search/projects";

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    List<String> jsonResultList = new ArrayList<>();
    for (String term : terms) {
      String queryTerm = encodeTerm(term);
      String jsonResult = curlProjects(API_KEY, queryTerm);
      jsonResultList.add(jsonResult);
    }
    String jsonBase = "{\"results\": [%s]}";
    String jsonResultString = String.format(jsonBase, String.join(",", jsonResultList));
    response.setContentType("application/json;");
    response.getWriter().println(jsonResultString);
  }

  private String encodeTerm(String term) {
    try {
      return URLEncoder.encode(term, StandardCharsets.UTF_8.toString());
    } catch (UnsupportedEncodingException ex) {
      throw new RuntimeException(ex.getCause());
    }
  }
  
  /**
   * Returns the a json string with the API response given a queryTerm and the API key.
   */
  private String curlProjects(String apiKey, String queryTerm) throws IOException {
    String queryString = String.format("?api_key=%s&q=%s", apiKey, queryTerm);
    String[] curlCommand = { "curl", "-H", "Accept: application/json", "-H", "Content-Type: application/json", "-X", "GET", API_PATH+queryString};

    ProcessBuilder process = new ProcessBuilder(curlCommand);
    Process p = process.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    StringBuilder builder = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      builder.append(line);
      builder.append(System.getProperty("line.separator"));
    }
    return builder.toString();
  }
}

@@ -1294,53 +1294,8 @@
   %7D%0A
-    String jsonBase = %22%7B%5C%22results%5C%22: %5B%25s%5D%7D%22;%0A
     
@@ -1338,16 +1338,29 @@
 mat(
-jsonBase
+%22%7B%5C%22results%5C%22: %5B%25s%5D%7D%22
 , St

Update ActionsServlet.java