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 Util.djonDBUtil;

import djondb.BSONArrayObj;
import djondb.BSONObj;
import djondb.DjondbConnection;

import requestHandlers.RequestHandler;

public class getReceiptImg_djon implements RequestHandler{
	private final String defaultImg = "./receiptsImgs/no_photo.jpg";

	@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);
		ret.put("img", defaultImg);
		DjondbConnection c;
		try
		{
			HttpSession session = req.getSession(false);
			c = djonDBUtil.openConn();
			BSONObj userDoc = djonDBUtil.getCurrentUser(session, c);
			int rid = Integer.parseInt(req.getParameter("rid"));
			if(userDoc != null)
			{
				BSONArrayObj receipts = userDoc.getBSONArray(djonDBUtil.USER_RECEIPTS_FIELDNAME);
				for(int i = 0; i<receipts.length(); ++i)
				{
					BSONObj receipt = receipts.get(i);
					if(rid == receipt.getInt(djonDBUtil.USER_RECEIPT_ID_FIELDNAME));
					{
						ret.put("img", receipt.getString(djonDBUtil.USER_RECEIPT_IMG_FIELDNAME));
						ret.put("ret", true);
					}
				}
			}
		}
		catch (Throwable theException) 	    
		{
		     System.out.println(theException); 
		}
		finally
		{
			out.print(ret);
			out.close();
		}		
	}

}
