package org.knitter.giftregistrylite;

import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;

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.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import static com.google.appengine.api.datastore.FetchOptions.Builder.*;

public class MakeFamilyMemberServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5706520902156989508L;

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		
		
		UserService userService = UserServiceFactory.getUserService();
	    User user = userService.getCurrentUser();
	    
	    if (user==null) {
	    	resp.sendRedirect("/");
	    }

	    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
	    Query qf = new Query("Family");
		Filter f1 = new FilterPredicate("name", FilterOperator.EQUAL, req.getParameter("f"));
		qf.setFilter(f1);
	    PreparedQuery pq = datastore.prepare(qf);
	    Entity family=pq.asSingleEntity();
	    
	    if (family == null) {
	    	// make a family
		    family = new Entity("Family");
		    family.setProperty("createdby", user);
		    family.setProperty("name", req.getParameter("f"));
		    family.setProperty("token", getToken());
		    datastore.put(family);
		    
		    // wait until the record shows up
		    int cnt=0; int limit=10;
		    while (cnt < 1 && limit-- > 0) {
		    	Query qf1 = new Query("Family");
		    	Filter f11 = new FilterPredicate("name", FilterOperator.EQUAL, req.getParameter("f"));
		    	qf1.setFilter(f11);
		    	PreparedQuery pq1 = datastore.prepare(qf1);
				cnt = pq1.countEntities(withLimit(10));
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
		    }
		    if (cnt == 0) {
		    	resp.sendRedirect("/");
		    	return;
		    }
	    } else {   
	    	if ( req.getParameter("t") == null || ! family.getProperty("token").equals(req.getParameter("t"))) {
	    		resp.sendRedirect("/");
	    		return;
	    	}
	    }
	    
	    Entity familymember = new Entity("FamilyMember", family.getKey());
	    familymember.setProperty("user", user);
	    familymember.setProperty("name", user.getNickname());
	    familymember.setProperty("family", family.getKey());
	    
	    datastore.put(familymember);
	    
    
	    // wait until the record shows up
	    int cnt=0; int limit=10;
	    while (cnt < 1 && limit-- > 0) {
	    		Query q = new Query("FamilyMember");
		    	Filter f11 = new FilterPredicate("user", FilterOperator.EQUAL, user);
		    	q.setFilter(f11);

	    		PreparedQuery pq1 = datastore.prepare(q);
				cnt = pq1.countEntities(withLimit(10));
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
	    }

    	resp.sendRedirect("/");

	}
	
	  private SecureRandom random = new SecureRandom();
	
	  private String getToken() {
	    return new BigInteger(40, random).toString(32);
	  }
	
}

@@ -1127,16 +1127,140 @@
 08L;%0D%0A%0D%0A
+%09public void doGet(HttpServletRequest req, HttpServletResponse resp)%0D%0A%09%09%09throws IOException %7B%0D%0A%09%09doPost(req, resp);%0D%0A%09%7D%0D%0A%09%0D%0A
 %09public 
@@ -1565,24 +1565,222 @@
 rect(%22/%22);%0D%0A
+%09    %09return;%0D%0A%09    %7D%0D%0A%09    %0D%0A%09    if (req.getParameter(%22f%22) == null %7C%7C req.getParameter(%22f%22).length() %3C 1) %7B%0D%0A%09    %09resp.sendRedirect(%22/?msg=Error:+You+must+supply+a+family+name%22);%0D%0A%09    %09return;%0D%0A
 %09    %7D%0D%0A%0D%0A%09 
@@ -3105,32 +3105,71 @@
 .sendRedirect(%22/
+?msg=Error:+Please+supply+a+valid+token
 %22);%0D%0A%09    %09%09retu

allow get for single url (emails)