// Copyright 2019 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.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.sps.Firebase;
import com.google.sps.Interactions;
import com.google.sps.Utils;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/load-event")
public class LoadEventServlet extends HttpServlet {

  private static final Logger LOGGER = Logger.getLogger(LoadEventServlet.class.getName());

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Key keyRequested;
    try {
      keyRequested = getEventKey(request);
    } catch (IllegalArgumentException | IOException e) {
      LOGGER.info("Could not retrieve event " + e);
      request.getRequestDispatcher("/WEB-INF/jsp/event-not-found.jsp").forward(request, response);
      return;
    }

    Query query = new Query("Event", keyRequested);
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity eventRequested = datastore.prepare(query).asSingleEntity();
    int alreadySaved = -1;

    String userToken = null;
    try {
      userToken = request.getParameter("userToken");
      if (userToken == null) {
        throw new IOException("No user token");
      }
    } catch (Exception e) {
      request = populateRequest(request, eventRequested, alreadySaved);
      request.getRequestDispatcher("/WEB-INF/jsp/display-event.jsp").forward(request, response);
      return;
    }

    String userID = null;
    Key userKey = null;
    try {
      if (Firebase.isUserLoggedIn(userToken)) {
        userID = Firebase.authenticateUser(userToken);
        userKey = KeyFactory.createKey("User", userID);
      } else {
        throw new IOException("User is not logged in.");
      }
    } catch (IllegalArgumentException | IOException e) {
      LOGGER.info("Login error: " + e);
      request = populateRequest(request, eventRequested, alreadySaved);
      request.getRequestDispatcher("/WEB-INF/jsp/display-event.jsp").forward(request, response);
      return;
    }

    Entity userEntity = null;
    try {
      userEntity = datastore.get(userKey);
      alreadySaved = UserServlet.alreadySaved(eventRequested.getKey().getId(), userEntity);
    } catch (EntityNotFoundException exception) {
      userEntity = Utils.makeUserEntity(userID, false);
      LOGGER.info("No entity found for " + userID + ", creating one now.");
      request = populateRequest(request, eventRequested, alreadySaved);
      request.getRequestDispatcher("/WEB-INF/jsp/display-event.jsp").forward(request, response);
      return;
    }

    List<String> tags = (List<String>) eventRequested.getProperty("tags");
    int delta =
        Interactions.recordInteraction(
            userID, keyRequested.getId(), Interactions.VIEW_SCORE, false);
    Interactions.updatePrefs(userEntity, tags, delta);
    datastore.put(userEntity);

    request = populateRequest(request, eventRequested, alreadySaved);
    request.getRequestDispatcher("/WEB-INF/jsp/display-event.jsp").forward(request, response);
  }

  /**
   * Supplies the request with attributes from the event requested.
   *
   * @return the request with attributes set.
   */
  private HttpServletRequest populateRequest(
      HttpServletRequest request, Entity event, int alreadySaved) {
    String name = event.getProperty("eventName").toString();
    String description = event.getProperty("eventDescription").toString();
    String date = event.getProperty("date").toString();
    String start = event.getProperty("startTime").toString();
    String end = event.getProperty("endTime").toString();
    String address = event.getProperty("address").toString();
    String tags = Utils.convertToJson(event.getProperty("tags"));
    String attendeeCount = event.getProperty("attendeeCount").toString();
    String key = event.getProperty("eventKey").toString();
    long eventId = event.getKey().getId();

    request.setAttribute("name", name);
    request.setAttribute("description", description);
    request.setAttribute("date", date);
    request.setAttribute("start", start);
    request.setAttribute("end", end);
    request.setAttribute("address", address);
    request.setAttribute("tags", tags);
    request.setAttribute("id", eventId);
    request.setAttribute("attendees", attendeeCount);
    request.setAttribute("saved", alreadySaved);
    request.setAttribute("key", key);

    return request;
  }

  /**
   * Retrieves the key string (if any) from the request parameter and converts it to type Key.
   *
   * @return the key from the request parameter.
   */
  private Key getEventKey(HttpServletRequest request) throws IllegalArgumentException, IOException {
    Key eventKey = null;

    if (request.getParameter("Event") == null) {
      throw new IOException("Request is missing parameter");
    }

    // Get the string from the request.
    String eventKeyString = request.getParameter("Event");

    // Convert String to type Key.
    eventKey = KeyFactory.stringToKey(eventKeyString);

    return eventKey;
  }
}

@@ -3319,100 +3319,8 @@
 y);%0A
-      alreadySaved = UserServlet.alreadySaved(eventRequested.getKey().getId(), userEntity);%0A
     
@@ -3505,192 +3505,100 @@
     
-  request = populateRequest(request, eventRequested, alreadySaved);%0A      request.getRequestDispatcher(%22/WEB-INF/jsp/display-event.jsp%22).forward(request, response);%0A      return;%0A    %7D
+%7D%0A%0A    alreadySaved = UserServlet.alreadySaved(eventRequested.getKey().getId(), userEntity);
 %0A%0A  

Remove return statement to prevent null entity users from saving events