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.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import java.io.PrintWriter;
import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");

    boolean isLoggedIn = false;

    PrintWriter out = response.getWriter();
    UserService userService = UserServiceFactory.getUserService();
    String loginUrl = userService.createLoginURL("/");

    if (userService.isUserLoggedIn()) {
      isLoggedIn = true;
      String userEmail = userService.getCurrentUser().getEmail();

      String nickname = getUserNickname(userService.getCurrentUser().getUserId());
      out.println("<p>Set your nickname here:</p>");
      out.println("<form method=\"POST\" action=\"/nickname\">");
      out.println("<input name=\"nickname\" value=\"" + nickname + "\" />");
      out.println("<br/>");
      out.println("<button>Submit</button>");
      out.println("</form>");

    
      response.getWriter().println("<p>Hello " + userEmail + "!</p>");
      response.getWriter().println("<p>Logout <a href=\"" + loginUrl + "\">here</a>.</p>");
    } else {

      response.getWriter().println("<p>Hello stranger.</p>");
      response.getWriter().println("<p>Login <a href=\"" + loginUrl + "\">here</a>.</p>");
    }

  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    if (!userService.isUserLoggedIn()) {
      response.sendRedirect("/login");
      return;
    }

    String nickname = request.getParameter("nickname");
    String id = userService.getCurrentUser().getUserId();
    String userEmail = userService.getCurrentUser().getEmail();

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity entity = new Entity("UserInfo", id);
    entity.setProperty("id", id);
    entity.setProperty("nickname", nickname);
    entity.setProperty("email", userEmail);
    // The put() function automatically inserts new data or updates existing data based on ID
    datastore.put(entity);

    response.sendRedirect("/");
  }

  /**
   * Returns the nickname of the user with id, or empty String if the user has not set a nickname.
   */
  private String getUserNickname(String id) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query query = new Query("blogMessage").addSort("time", SortDirection.DESCENDING);
    PreparedQuery results = datastore.prepare(query);
    Entity entity = results.asSingleEntity();
    if (entity == null) {
      return "";
    }
    String nickname = (String) entity.getProperty("nickname");
    return nickname;
  }
}

@@ -1384,16 +1384,234 @@
 rId());%0A
+    %0A      if (nickname == %22%22)%7B out.println(%22%3Cp%3EYou don't have a nickname%3C/p%3E%22);%0A      %7D else %7B out.println(%22%3Cp%3EYour current nickname is %22 + nickname + %22. If you'd like to change it, enter a new one below.%3C/p%3E%22);%7D   %0A%0A
       ou
@@ -1706,24 +1706,21 @@
 tion=%5C%22/
-nickname
+login
 %5C%22%3E%22);%0A 
@@ -2538,24 +2538,24 @@
  String 
-nickname
+NICKNAME
  = reque
@@ -2822,16 +2822,19 @@
 ty(%22
-UserInfo
+blogMessage
 %22, i
@@ -2906,24 +2906,24 @@
 kname%22, 
-nickname
+NICKNAME
 );%0A    e
@@ -2969,273 +2969,68 @@
     
-// The put() function automatically inserts new data or updates existing data based on ID%0A    datastore.put(entity);%0A%0A    response.sendRedirect(%22/%22);%0A  %7D%0A%0A  /**%0A   * Returns the nickname of the user with id, or empty String if the user has not set a nickname.%0A   */
+datastore.put(entity);%0A%0A    response.sendRedirect(%22/%22);%0A  %7D%0A
 %0A  p
@@ -3169,16 +3169,24 @@
  query =
+%0A       
  new Que
@@ -3206,49 +3206,95 @@
 ge%22)
-.addSort(%22time%22, SortDirection.DESCENDING
+%0A            .setFilter(new Query.FilterPredicate(%22id%22, Query.FilterOperator.EQUAL, id)
 );%0A 
@@ -3452,24 +3452,24 @@
  String 
-nickname
+NICKNAME
  = (Stri
@@ -3515,24 +3515,24 @@
  return 
-nickname
+NICKNAME
 ;%0A  %7D%0A%7D%0A

Update entity inside post method to properly keep track of nickname. Update string constant naming. Update functuon getUserNickname to set nickname parameter by using id/ .