package requestHandlers.djonDB;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;

import requestHandlers.RequestHandler;
import Util.djonDBUtil;
import djondb.BSONArrayObj;
import djondb.BSONObj;
import djondb.DjondbConnection;

public class addReceipt_djon 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();
		ret.put("ret", false);
		DjondbConnection c;
		try
		{
			String cardID = req.getParameter("card");
			String merchantName = req.getParameter("merchantName");
			String purchaseDate = req.getParameter("date");

			System.out.println("cardID = " + cardID);
			System.out.println("merchantName = " + merchantName);
			System.out.println("purchaseDate = " + purchaseDate);
			
			HttpSession session = req.getSession(false);
			c = djonDBUtil.openConn();
			BSONObj userDoc = djonDBUtil.getCurrentUser(session, c);
			if(userDoc != null)
			{
				BSONArrayObj receipts = userDoc.getBSONArray(djonDBUtil.USER_RECEIPTS_FIELDNAME);
				BSONObj receipt = new BSONObj();
				int id = receipts.length();
				System.err.println("rid = " + id);
				receipt.add(djonDBUtil.USER_RECEIPT_ID_FIELDNAME, id);
				receipt.add(djonDBUtil.USER_RECEIPT_MERCHANT_FIELDNAME, merchantName);
				receipt.add(djonDBUtil.USER_RECEIPT_PURCHASEDATE_FIELDNAME, purchaseDate);
				receipt.add(djonDBUtil.USER_RECEIPT_CARD_FIELDNAME, cardID);
				receipt.add(djonDBUtil.USER_RECEIPT_ITEMS_FIELDNAME, new BSONArrayObj());
				receipt.add(djonDBUtil.USER_RECEIPT_IMG_FIELDNAME, "./receiptsImgs/"+id+".jpg");
				receipt.add(djonDBUtil.USER_RECEIPT_TOTAL_FIELDNAME, 0.0);		
				receipts.add(receipt);
				c.update(djonDBUtil.DBNAME, djonDBUtil.USERS_COLLECTION_NAME, userDoc);
				ret.put("ret", true);
			}
		}
		catch(NullPointerException npe)
		{
			System.err.println(npe);
		}
		catch(NumberFormatException nfe)
		{
			System.err.println(nfe);
		}
		catch (Throwable theException) 	    
		{
		     System.out.println(theException); 
		}
		finally
		{
			out.print(ret);
			out.close();
		}		
	}

}
