// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.lecturechat.servlets;

import com.google.gson.Gson;
import com.google.lecturechat.data.AuthStatus;
import com.google.lecturechat.data.DatastoreAccess;
import com.google.lecturechat.data.Event;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Optional;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.BadRequestException;

/**
 * Servlet for joining an event and listing all the events that the user joined from all the groups
 * or from just one particular group specified by its id.
 */
@WebServlet("/joined-events")
public class JoinedEventsServlet extends HttpServlet {

  private static final String EVENT_ID_PARAMETER = "event-id";
  private static final String BEGINNING_DATE_PARAMETER = "beginning-date";
  private static final String ENDING_DATE_PARAMETER = "ending-date";
  private static final String GROUP_ID_PARAMETER = "group-id";
  private static DatastoreAccess datastore;

  @Override
  public void init() {
    datastore = DatastoreAccess.getDatastoreAccess();
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Optional<String> userId = AuthStatus.getUserId(request);

    if (!userId.isPresent()) {
      return;
    }

    List<Event> events;
    String groupId = request.getParameter(GROUP_ID_PARAMETER);

    if (groupId == null) {
      events = datastore.getJoinedEvents(userId.get());
      String beginningDate = request.getParameter(BEGINNING_DATE_PARAMETER);
      String endingDate = request.getParameter(ENDING_DATE_PARAMETER);

      if (beginningDate == null || endingDate == null) {
        return;
      }

      try {
        events = datastore.getJoinedEventsThatStartBetweenDates(Long.parseLong(beginningDate),
            Long.parseLong(endingDate), userId.get());
      } catch (NumberFormatException e) {
        throw new BadRequestException(e.getMessage());
      }
    } else {
      try {
        events = datastore.getAllJoinedEventsFromGroup(Long.parseLong(groupId), userId.get());
      } catch (NumberFormatException e) {
        throw new BadRequestException(e.getMessage());
      }
    }

    response.setContentType("application/json;");
    response.setCharacterEncoding("UTF-8");
    Gson gson = new Gson();
    response.getWriter().println(gson.toJson(events));
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Optional<String> userId = AuthStatus.getUserId(request);

    if (!userId.isPresent()) {
      return;
    }

    try {
      long eventId = Long.parseLong(request.getParameter(EVENT_ID_PARAMETER));
      datastore.joinEvent(userId.get(), eventId);
    } catch (NumberFormatException e) {
      throw new BadRequestException(e.getMessage());
    }
  }
}

@@ -2086,24 +2086,36 @@
 ARAMETER);%0A%0A
+    try %7B%0A  
     if (grou
@@ -2118,17 +2118,17 @@
 groupId 
-=
+!
 = null) 
@@ -2131,24 +2131,26 @@
 ll) %7B%0A      
+ 
+ 
 events = dat
@@ -2151,32 +2151,35 @@
  = datastore.get
+All
 JoinedEvents(use
@@ -2174,17 +2174,50 @@
 edEvents
-(
+FromGroup(Long.parseLong(groupId),
 userId.g
@@ -2219,24 +2219,41 @@
 rId.get());%0A
+      %7D else %7B%0A  
       String
@@ -2319,24 +2319,26 @@
 TER);%0A      
+ 
+ 
 String endin
@@ -2393,24 +2393,26 @@
 ER);%0A%0A      
+  
 if (beginnin
@@ -2442,32 +2442,34 @@
 Date == null) %7B%0A
+  
         return;%0A
@@ -2478,22 +2478,11 @@
     
-%7D%0A%0A      try %7B
+  %7D
 %0A   
@@ -2639,228 +2639,9 @@
    %7D
- catch (NumberFormatException e) %7B%0A        throw new BadRequestException(e.getMessage());%0A      %7D%0A    %7D else %7B%0A      try %7B%0A        events = datastore.getAllJoinedEventsFromGroup(Long.parseLong(groupId), userId.get());%0A  
+%0A
     
@@ -2678,26 +2678,24 @@
  e) %7B%0A      
- 
- 
 throw new Ba
@@ -2725,32 +2725,24 @@
 Message());%0A
-      %7D%0A
     %7D%0A%0A    r

Restructure try catch