package requestHandlers;

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

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 addItem implements RequestHandler{
	private final String addSql = "INSERT INTO R2LineItem(ReceiptID, ItemName, ItemPrice, ItemQty, ItemTaxRate, UserID) " +
			"VALUES(?, ?, ?, ?, ?, ?)";
	@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;
		ret.put("ret", false);
		
		int rid = req.getParameter("rid") != null && !req.getParameter("rid").equals("") ? Integer.parseInt(req.getParameter("rid")) : -1;
		String itemName = req.getParameter("name");
		double itemPrice = req.getParameter("price") != null && !req.getParameter("price").equals("") ? Double.parseDouble(req.getParameter("price")) : -1.0;
		int qty = req.getParameter("qty") != null && !req.getParameter("qty").equals("") ? Integer.parseInt(req.getParameter("qty")) : -1;
		double taxRate = req.getParameter("taxRate") != null && !req.getParameter("taxRate").equals("") ? Double.parseDouble(req.getParameter("taxRate")) : -1.0;
		System.out.println("rid = " + rid);
		System.out.println("itemName = " + itemName);
		System.out.println("itemPrice = " + itemPrice);
		System.out.println("taxRate = " + taxRate);
		System.out.println("Qty = " + qty);
		if(itemPrice > 0 && rid>0 && qty>0 && taxRate>=0.0 && itemName != null && !itemName.equals(""))
		{
			try
			{
				HttpSession session = req.getSession(false);
				if(session != null)
				{
					R2UserBean userbean = (R2UserBean)session.getAttribute("currentSessionUser");
					if(userbean != null)
					{
						con = ConnectionManager.getConnection();
						stmt = con.prepareStatement(addSql);
						int index = 1;
						stmt.setInt(index++, rid);
						stmt.setString(index++, itemName);
						stmt.setDouble(index++, itemPrice);
						stmt.setInt(index++, qty);
						stmt.setDouble(index++, taxRate);
						stmt.setInt(index++, userbean.getUserID());
						if(stmt.execute())
						{
							ret.put("ret", true);
						}
					}
				}
			}
			catch (Throwable theException) 	    
			{
			     System.out.println(theException); 
			}
			finally
			{
				/*System.out.println("ret json:");
				System.out.println(ret);*/
				DBUtil.closeStmt(stmt);
				DBUtil.closeConnection(con);
			}
		}
		out.print(ret);
		out.close();
		
	}

}
