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 addReceipt implements RequestHandler
{
	private final String addSql = "INSERT INTO R2Receipt(ReceiptID, UserID, CardID, MerchantID, PurchaseDate) " +
			                      "VALUES(?, ?, ?, ?, ?)";
	private final String getMerchantIDSql = "SELECT MAX(ReceiptID) AS id FROM R2Receipt WHERE 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;
		PreparedStatement stmt2 = null;
		ResultSet rs = null;
		ret.put("ret", false);
		try
			{
				String cardID = req.getParameter("card");
				int merchantID = Integer.parseInt(req.getParameter("merchant"));
				String purchaseDate = req.getParameter("purchaseDate");

				System.out.println("cardID = " + cardID);
				System.out.println("merchantID = " + merchantID);
				System.out.println("purchaseDate = " + purchaseDate);
				
				HttpSession session = req.getSession(false);
				if(session != null)
				{
					R2UserBean userbean = (R2UserBean)session.getAttribute("currentSessionUser");
					if(userbean != null)
					{
						con = ConnectionManager.getConnection();
						stmt = con.prepareStatement(getMerchantIDSql);
						stmt.setString(1, userbean.getEmail());
						rs = stmt.executeQuery();
						
						if(rs.first())
						{
							int id = rs.getInt(1) + 1;
							System.out.println("id = " + id);
							int index = 1;
							stmt2 = con.prepareStatement(addSql);
							stmt2.setInt(index++, id);
							stmt2.setInt(index++, userbean.getUserID());
							stmt2.setString(index++, cardID);
							stmt2.setInt(index++, merchantID);
							stmt2.setString(index++, purchaseDate);
							if(stmt2.execute())
							{
								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
			{
				/*System.out.println("ret json:");
				System.out.println(ret);*/
				DBUtil.closeResultSet(rs);
				DBUtil.closeStmt(stmt);
				DBUtil.closeStmt(stmt2);
				DBUtil.closeConnection(con);
				out.print(ret);
				out.close();
			}
	}

}
