package com.google.sps.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.repackaged.com.google.common.collect.Iterables;

/**
 * This servlet is called weekly to delete the top challenge suggestion so that
 * the new weekly challenge can be updated to be the next top voted suggestion
 * following the one that has just been deleted.
 *
 * @author lucyqu
 *
 */
@WebServlet("delete-top-option")
public class DeletePollOptionServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query query = new Query("Option").addSort("timestamp", SortDirection.ASCENDING);
    PreparedQuery results = datastore.prepare(query);
    long maxVotedId = this.getMaxVotedId(results);
    this.deleteEntity(maxVotedId, results, datastore);
  }

  /**
   * Sets the variables maxVotes and maxVotesId by iterating through the entities.
   *
   * @param results queried results
   * @return maxVotesId the id of option with maximum number of votes
   */
  private long getMaxVotedId(PreparedQuery results) {
    long maxVotedId = 0;
    int maxVotes = 0;
    Iterable<Entity> resultsIterable = results.asIterable();
    // Set maxVotedId to be first one in iterable of Entities
    if (Iterables.size(resultsIterable) > 0) {
      maxVotedId = results.asIterable().iterator().next().getKey().getId();
    }
    /*
     * Update maxVotes and maxVotedId by iterating through Entities, checking for
     * max votes
     */
    for (Entity entity : resultsIterable) {
      long id = entity.getKey().getId();
      List<String> votes = (ArrayList<String>) entity.getProperty("votes");
      int numVotes = (votes != null) ? votes.size() : 0;
      if (numVotes > maxVotes) {
        maxVotes = numVotes;
        maxVotedId = id;
      }
    }
    return maxVotedId;
  }

  /**
   * Deletes the option entity with the maximum number of votes.
   *
   * @param results   queried results
   * @param datastore database storing information
   */
  private void deleteEntity(long maxVotedId, PreparedQuery results, DatastoreService datastore) {
    for (Entity optionEntity : results.asIterable()) {
      Key optionEntityKey = optionEntity.getKey();
      if (optionEntityKey.getId() == maxVotedId) {
        datastore.delete(optionEntityKey);
        break;
      }
    }
  }
}

@@ -508,16 +508,70 @@
 re.Key;%0A
+import com.google.appengine.api.datastore.KeyFactory;%0A
 import c
@@ -615,24 +615,24 @@
 paredQuery;%0A
-
 import com.g
@@ -891,19 +891,16 @@
  so that
-%0A *
  the new
@@ -906,16 +906,19 @@
 w weekly
+%0A *
  challen
@@ -970,19 +970,16 @@
 ggestion
-%0A *
  followi
@@ -1007,16 +1007,19 @@
 ust been
+%0A *
  deleted
@@ -1041,19 +1041,16 @@
  lucyqu%0A
- *%0A
  */%0A@Web
@@ -1572,16 +1572,26 @@
 atastore
+, response
 );%0A  %7D%0A%0A
@@ -2706,18 +2706,16 @@
 results 
-  
 queried 
@@ -2807,16 +2807,23 @@
 eEntity(
+%0A      
 long max
@@ -2830,16 +2830,22 @@
 VotedId,
+%0A     
  Prepare
@@ -2859,16 +2859,22 @@
 results,
+%0A     
  Datasto
@@ -2896,71 +2896,52 @@
 tore
-) %7B
+,
 %0A    
-for (Entity optionEntity : results.asIterable()
+  HttpServletResponse response
 ) %7B%0A    
   Ke
@@ -2936,18 +2936,16 @@
 ) %7B%0A    
- 
- 
 Key opti
@@ -2950,79 +2950,44 @@
 tion
-EntityKey = optionEntity.getKey();%0A      if (optionEntityKey.getId() ==
+Key = KeyFactory.createKey(%22Option%22,
  max
@@ -2994,23 +2994,18 @@
 VotedId)
- %7B%0A    
+;%0A
     data
@@ -3027,48 +3027,13 @@
 tion
-EntityKey);%0A        break;%0A      %7D%0A    %7D
+Key);
 %0A  %7D

make deletepollservlet o(1) instead of o(n)