package requestHandlers.djonDB;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

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

import org.json.JSONArray;
import org.json.JSONObject;

import Util.djonDBUtil;
import djondb.BSONArrayObj;
import djondb.BSONObj;
import djondb.DjondbConnection;
import djondb.Loader;

/**
 * Servlet implementation class djonTest
 */
@WebServlet("/djonTest")
public class djonTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public djonTest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
		JSONObject ret = new JSONObject();
		Set<Integer> yearset = new TreeSet<Integer>(Collections.reverseOrder());
		JSONArray years = new JSONArray();
		DjondbConnection c = null;
		try
		{
			Loader.initialize();
			c = djonDBUtil.openConn();
			BSONArrayObj userArr = c.find(djonDBUtil.DBNAME, djonDBUtil.USERS_COLLECTION_NAME, "$'email' == 'djiang1@student.gsu.edu' and $'_id' == 'dddac36a-ac7b-4d85-beb5-bc5c94b3a888'");
			BSONObj userDoc = userArr.get(0);
			if(userDoc != null)
			{
				BSONArrayObj receiptArr = userDoc.getBSONArray(djonDBUtil.USER_RECEIPTS_FIELDNAME);
				if(receiptArr != null && receiptArr.length() > 0)
				{
					for(int i = 0; i<receiptArr.length(); ++i)
					{
						BSONObj receipt = receiptArr.get(i);
						String date = receipt.getString(djonDBUtil.USER_RECEIPT_PURCHASEDATE_FIELDNAME);
						yearset.add(Integer.parseInt(date.substring(0, 4)));
					}
				}
				for(Integer year : yearset)
				{
					years.put(year);
				}
			}
			ret.put("years", years);
		}
		catch (Throwable theException) 	    
		{
		     System.out.println(theException); 
		}
		finally
		{
			djonDBUtil.closeConn(c);
			out.print(ret);
			out.close();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
