package requestHandlers;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

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

import org.json.JSONObject;

import Beans.R2UserBean;
import Util.ConnectionManager;
import Util.DBUtil;

public class getReceipts implements RequestHandler{
	private String sql = "SELECT ReceiptID, CardID, PurchaseDate, MerchantName FROM R2Receipt, R2Merchant WHERE R2Merchant.MerchantID=R2Receipt.MerchantID AND UserID = (SELECT UserID FROM R2User WHERE Email=?)";
	@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();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		ret.put("ret", false);
		ret.put("receipts", "{}");
		try
		{
			HttpSession session = req.getSession(false);
			if(session != null)
			{
				R2UserBean userbean = (R2UserBean)session.getAttribute("currentSessionUser");
				if(userbean != null)
				{
					con = ConnectionManager.getConnection();
					stmt = con.prepareStatement(sql);
					stmt.setString(1, userbean.getEmail());
					rs = stmt.executeQuery();
					if(rs != null)
					{
						JSONObject obj = new JSONObject();
						while(rs.next())
						{
							obj.put(rs.getObject("ReceiptID").toString(), rs.getString("MerchantName") + ":" + rs.getDate("PurchaseDate").toString() + ":" + rs.getObject("CardID"));
						}
						ret.put("receipts", obj);
						ret.put("ret", true);
					}
				}
			}
		}
		catch (Throwable theException) 	    
		{
		     System.out.println(theException); 
		}
		finally
		{
			/*System.out.println("ret json:");
			System.out.println(ret);*/
			DBUtil.closeResultSet(rs);
			DBUtil.closeStmt(stmt);
			DBUtil.closeConnection(con);
			out.print(ret);
			out.close();
		}
	}

}
