package com.google.sps.servlets;

import com.google.cloud.Date;
import com.google.gson.Gson;
import com.google.sps.data.Event;
import com.google.sps.data.User;
import com.google.sps.utilities.CommonUtils;
import com.google.sps.utilities.NlpProcessing;
import com.google.sps.utilities.PrefilledInformationConstants;
import com.google.sps.utilities.SpannerTasks;
import java.io.IOException;
import java.lang.StringBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.cloud.language.v1.Document;
import com.google.cloud.language.v1.LanguageServiceClient;
import com.google.cloud.language.v1.ClassifyTextRequest;
import com.google.cloud.language.v1.ClassifyTextResponse;
import com.google.cloud.language.v1.ClassificationCategory;
import com.google.cloud.language.v1.Document.Type;

@WebServlet("/create-event")
public class EventCreationServlet extends HttpServlet {
  /** Returns event details from database */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String eventId = request.getParameter("eventId");
    Optional<Event> eventOptional = SpannerTasks.getEventById(eventId);

    // If event DNE, sends 404 ERR to frontend
    if (eventOptional.isPresent()) {
      Event event = eventOptional.get();
      response.setContentType("text/html;");
      response.getWriter().println(new Gson().toJson(event));
    } else {
      response.sendError(
          HttpServletResponse.SC_NOT_FOUND,
          String.format("No events found with event ID %s", eventId));
    }
  }

  /** Posts newly created event to database with NLP suggested labels and redirects to page with created event details*/
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String name = request.getParameter("name");
    String[] parsedDate = request.getParameter("date").split("/");
    Date date =
         Date.fromYearMonthDay(
            /*Year=*/ Integer.parseInt(parsedDate[2]),
            /*Month=*/ Integer.parseInt(parsedDate[0]),
            /*Day=*/ Integer.parseInt(parsedDate[1]));
    String time = request.getParameter("time");
    String description = request.getParameter("description");
    String location = request.getParameter("location");
    String text = new StringBuilder().append(name).append(" ").append(description).toString();

    ArrayList<String> categoryNames = new ArrayList<String>();

    // Call NLP API (only works if more than 20 words in text)
    if (text.trim().split("\\s+").length > 20) {
        categoryNames = NlpProcessing.getNlp(text);
    }

    // Add user inputted and NLP suggested labels together
    Set<String> labels = new HashSet<>();
    labels.addAll(new HashSet<>(categoryNames));
    labels.addAll(new HashSet<>(splitAsList(request.getParameter("interests"))));

    User host = SpannerTasks.getLoggedInUser().get();
    Event event = new Event.Builder(name, description, labels, location, date, time, host).build();
    SpannerTasks.insertorUpdateEvent(event);

    String redirectUrl = "/event-details.html?eventId=" + event.getId();
    response.sendRedirect(redirectUrl);
    // Event in database
    response.getWriter().println(CommonUtils.convertToJson(SpannerTasks.getEventById(event.getId()).get().toBuilder().build()));
  }

// /*
//  * @param text: String of text that includes event name and description
//  * @return categoryNames: returns selected names of labels that NLP API suggests for text
// */
//   public ArrayList<String> getNlp(String text) throws IOException {
//     ArrayList<String> categoryNames = new ArrayList<String>();

//     // Use Gcloud NLP API to predict labels based on user inputted event name and description
//     try (LanguageServiceClient language = LanguageServiceClient.create()) {     
//     Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
//     ClassifyTextRequest req = ClassifyTextRequest.newBuilder().setDocument(doc).build();
//     // Detect categories in the given text
//     ClassifyTextResponse res = language.classifyText(req);
//         for (ClassificationCategory category : res.getCategoriesList()) {
//             String categoryName = category.getName().split("/")[1];
//             if (category.getConfidence() >= 0.5 && PrefilledInformationConstants.INTERESTS.contains(categoryName) ) {
//                 categoryNames.add(categoryName);
//             }
//         }
//     } 
//     return categoryNames;
//   }

  private static List<String> splitAsList(String values) {
    return Arrays.asList(values.split("\\s*,\\s*"));
  }
}

@@ -2696,243 +2696,8 @@
 );%0A%0A
-    ArrayList%3CString%3E categoryNames = new ArrayList%3CString%3E();%0A%0A    // Call NLP API (only works if more than 20 words in text)%0A    if (text.trim().split(%22%5C%5Cs+%22).length %3E 20) %7B%0A        categoryNames = NlpProcessing.getNlp(text);%0A    %7D%0A%0A
     
@@ -2825,29 +2825,69 @@
 shSet%3C%3E(
-categoryNames
+getNlpSuggestedFilters(text, new ArrayList%3CString%3E())
 ));%0A    
@@ -3441,16 +3441,82 @@
  %7D%0A%0A
-// /*%0A//
+  /* Calls to get NLP Suggested filters if applicable (20 words or more)%0A 
   * 
@@ -3584,18 +3584,17 @@
 ription%0A
-//
+ 
   * @ret
@@ -3679,18 +3679,45 @@
 text
-%0A//
+ if available, else empty list%0A  
  */%0A
-// 
   pu
@@ -3749,950 +3749,225 @@
 tNlp
-(String text) throws IOException %7B%0A//     ArrayList%3CString%3E categoryNames = new ArrayList%3CString%3E();%0A%0A//     // Use Gcloud NLP API to predict labels based on user inputted event name and description%0A//     try (LanguageServiceClient language = LanguageServiceClient.create()) %7B     %0A//     Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();%0A//     ClassifyTextRequest req = ClassifyTextRequest.newBuilder().setDocument(doc).build();%0A//     // Detect categories in the given text%0A//     ClassifyTextResponse res = language.classifyText(req);%0A//         for (ClassificationCategory category : res.getCategoriesList()) %7B%0A//             String categoryName = category.getName().split(%22/%22)%5B1%5D;%0A//             if (category.getConfidence() %3E= 0.5 && PrefilledInformationConstants.INTERESTS.contains(categoryName) ) %7B%0A//                 categoryNames.add(categoryName);%0A//          
+SuggestedFilters(String text, ArrayList%3CString%3E categoryNames) throws IOException%7B%0A  if (text.trim().split(%22%5C%5Cs+%22).length %3E 20) %7B%0A    NlpProcessing nlp = new NlpProcessing();%0A    categoryNames = nlp.getNlp(text);%0A
   
- 
 %7D%0A
-//         %7D%0A//     %7D %0A// 
     
@@ -3988,19 +3988,16 @@
 yNames;%0A
-// 
   %7D%0A%0A  p

abstract away nlp func