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.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.firebase.auth.FirebaseAuth;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Once class owner submits a TA email, retrieve that user and add them as a TA to the class
@WebServlet("/submit-roster")
public class SubmitRoster extends HttpServlet {

  private FirebaseAuth authInstance;

  // Get the current session
  @Override
  public void init(ServletConfig config) throws ServletException {
    try {
      authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp());
    } catch (IOException e) {
      throw new ServletException(e);
    }
  }

  // Add a user to the datastore
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    String rosterNames = request.getParameter("roster").trim();

    // Split the emails and collapse whitespaces
    List<String> allClassEmails = Arrays.asList(rosterNames.split("\\s*,\\s*"));

    // Find the corresponding class Key
    String classCode = request.getParameter("classCode").trim();
    Key classKey = KeyFactory.stringToKey(classCode);
    ArrayList<Key> registered = new ArrayList<Key>();
    registered.add(classKey);

    for (String email : allClassEmails) {
      // Prevent creating duplicate users
      Query query =
          new Query("User")
              .setFilter(new FilterPredicate("userEmail", FilterOperator.EQUAL, email));

      if (datastore.prepare(query).countEntities() == 0) {

        Entity user = new Entity("User");
        user.setProperty("userEmail", email);
        user.setProperty("registeredClasses", registered);
        user.setProperty("ownedClasses", Collections.emptyList());
        user.setProperty("taClasses", Collections.emptyList());

        datastore.put(user);
      } else {
        // Entity user = query.asSingleEntity();
      }
    }

    // Redirect to the class dashboard page
    response.sendRedirect("/dashboard.html?classCode=" + classCode);
  }
}

@@ -297,32 +297,89 @@
 ore.KeyFactory;%0A
+import com.google.appengine.api.datastore.PreparedQuery;%0A
 import com.googl
@@ -669,36 +669,8 @@
 on;%0A
-import java.util.ArrayList;%0A
 impo
@@ -1029,70 +1029,68 @@
 s a 
-TA email, retrieve that user and add them as a TA to the class
+roster, add or update those student users class registration
 %0A@We
@@ -1486,16 +1486,24 @@
 / Add a 
+student 
 user to 
@@ -2069,197 +2069,163 @@
 e);%0A
-    ArrayList%3CKey%3E registered = new ArrayList%3CKey%3E();%0A    registered.add(classKey);%0A%0A    for (String email : allClassEmails) %7B%0A      // Prevent creating duplicate users%0A      Query query =%0A
+%0A    for (String email : allClassEmails) %7B%0A      // Look for the TA in the user datastore%0A      PreparedQuery queryUser =%0A          datastore.prepare(%0A    
     
@@ -2248,16 +2248,20 @@
 %22User%22)%0A
+    
         
@@ -2339,16 +2339,17 @@
  email))
+)
 ;%0A%0A     
@@ -2353,36 +2353,106 @@
     
-if (datastore.prepare
+Entity user;%0A%0A      // If the student user entity doesnt exist yet, create one%0A      if 
 (query
-)
+User
 .cou
@@ -2477,30 +2477,84 @@
  %7B%0A%0A        
-Entity
+List%3CKey%3E regClassesList = Arrays.asList(classKey);%0A%0A       
  user = new 
@@ -2664,23 +2664,27 @@
 es%22, reg
-istered
+ClassesList
 );%0A     
@@ -2846,16 +2846,93 @@
 %0A      %7D
+%0A      // If student already exists, update their registered class list%0A     
  else %7B%0A
@@ -2942,18 +2942,8 @@
     
- // Entity
  use
@@ -2951,16 +2951,20 @@
  = query
+User
 .asSingl
@@ -2970,24 +2970,241 @@
 leEntity();%0A
+        List%3CKey%3E regClassesList = (List%3CKey%3E) user.getProperty(%22registeredClasses%22);%0A        regClassesList.add(classKey);%0A        user.setProperty(%22registeredClasses%22, regClassesList);%0A%0A        datastore.put(user);%0A
       %7D%0A    

Add comments to roster servlet.