package requestHandlers.mongoDB;

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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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

import requestHandlers.RequestHandler;
import Util.MongoDBUtil;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

public class getRecordYears_mongo implements RequestHandler{

	@Override
	public void processRequest(Object user, HttpServletRequest req,
			HttpServletResponse res, Object[] services, Object log)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = res.getWriter();
		JSONObject ret = new JSONObject();
		Set<Integer> yearset = new TreeSet<Integer>(Collections.reverseOrder());
		JSONArray years = new JSONArray();
		MongoClient c;
		try
		{
			HttpSession session = req.getSession(false);
			c = MongoDBUtil.openConn();
			DBObject userDoc = MongoDBUtil.getCurrentUser(session, c);
			if(userDoc != null)
			{
				BasicDBList receipts = (BasicDBList) userDoc.get(MongoDBUtil.USER_RECEIPTS_FIELDNAME);
				if(receipts != null && receipts.size() > 0)
				{
					for(int i=0; i<receipts.size(); ++i)
					{
						BasicDBObject receipt = (BasicDBObject)receipts.get(i);
						String date = receipt.getString(MongoDBUtil.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
		{
			out.print(ret);
			out.close();
		}		
	}

}
