package requestHandlers.djonDB;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

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

import org.json.JSONArray;
import org.json.JSONObject;

import requestHandlers.RequestHandler;
import Util.ReceiptDateComparator;
import Util.ReceiptNumberComparator;
import Util.ReceiptStringComparator;
import Util.djonDBUtil;
import djondb.BSONArrayObj;
import djondb.BSONObj;
import djondb.DjondbConnection;

public class getItems_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();

		JSONArray rows = new JSONArray();
		JSONArray temp = new JSONArray();
		ret.put("ret", false);
		ret.put("page", 1);
		ret.put("total", 0);
		ret.put("records", 0);
		ret.put("rows", rows);
		DjondbConnection c;
		try
		{
			HttpSession session = req.getSession(false);
			c = djonDBUtil.openConn();
			BSONObj userDoc = djonDBUtil.getCurrentUser(session, c);
			if(userDoc != null)
			{
				int rid = -1;
				int page = 1;
				int limit = 5;
				try
				{
					rid = req.getParameter("rid") == null || req.getParameter("rid").equals("") ? -1 : Integer.parseInt(req.getParameter("rid"));
					page = req.getParameter("page") == null || req.getParameter("page").equals("") ? 1 : Integer.parseInt(req.getParameter("page")); // get the requested page
					limit = req.getParameter("rows") == null || req.getParameter("rows").equals("") ? 5 : Integer.parseInt(req.getParameter("rows"));
				}catch(NumberFormatException nfe)
				{
					System.err.println(nfe);
				}
				
				String sidx = req.getParameter("sidx") == null || req.getParameter("sidx").equals("") ? "date" : req.getParameter("sidx");
				String sord = req.getParameter("sord") == null || req.getParameter("sord").equals("") ? "asc" : req.getParameter("sord");

				System.out.println("page = " + req.getParameter("page"));
				System.out.println("limit = " + req.getParameter("rows"));
				System.out.println("sidx = " + req.getParameter("sidx"));
				System.out.println("sord = " + req.getParameter("sord"));
				
				// search request
				boolean _search = req.getParameter("_search") == null || req.getParameter("_search").equals("") ? false : Boolean.parseBoolean(req.getParameter("_search"));
				String field = req.getParameter("searchField");
				String oper = req.getParameter("searchOper");
				String str = req.getParameter("searchString");
				
				BSONArrayObj receipts = userDoc.getBSONArray(djonDBUtil.USER_RECEIPTS_FIELDNAME);
				for(int i = 0; i<receipts.length(); ++i)
				{
					BSONObj receipt = receipts.get(i);
					int RID = receipt.getInt(djonDBUtil.USER_RECEIPT_ID_FIELDNAME);
					if(rid == RID)
					{
						System.out.println("rid = " + rid + " receitpid = " + RID);
						
						BSONArrayObj items = receipt.getBSONArray(djonDBUtil.USER_RECEIPT_ITEMS_FIELDNAME);
						int count = items.length();
						int total_pages = 1;
						if(count > 0 && limit > 0)
						{
							total_pages = count / limit;
							if(count % limit > 0)
								total_pages++;
						}
						if(page > total_pages)
						{
							page = total_pages;
						}
						int start = limit * page - limit;
						if(start < 0)
						{
							start = 0;
						}
						int end = start + limit;
						if(end > items.length())
							end = items.length();
						
						BSONObj[] arr = new BSONObj[items.length()];
						for(int t=0; t<arr.length; ++t)
						{
							arr[t] = items.get(t);
						}
						
						if(sidx.equals("item"))
						{
							Arrays.sort(arr, new ReceiptStringComparator(sord, djonDBUtil.USER_ITEM_NAME_FIELDNAME));
						}
						else if(sidx.equals("price"))
						{
							Arrays.sort(arr, new ReceiptNumberComparator(sord, djonDBUtil.USER_ITEM_PRICE_FIELDNAME));
						}
						else if(sidx.equals("qty"))
						{
							Arrays.sort(arr, new ReceiptNumberComparator(sord, djonDBUtil.USER_ITEM_QTY_FIELDNAME));
						}
						else if(sidx.equals("taxRate"))
						{
							Arrays.sort(arr, new ReceiptNumberComparator(sord, djonDBUtil.USER_ITEM_TAXRATE_FIELDNAME));
						}
						
						for(int j=start; j<end; ++j)
						{
							//BSONObj item = items.get(j);
							BSONObj item = arr[j];
							JSONArray record = new JSONArray();
							double p = item.getDouble(djonDBUtil.USER_ITEM_PRICE_FIELDNAME);
							double q = item.getDouble(djonDBUtil.USER_ITEM_QTY_FIELDNAME);
							double t = item.getDouble(djonDBUtil.USER_ITEM_TAXRATE_FIELDNAME);
							record.put(item.getString(djonDBUtil.USER_ITEM_NAME_FIELDNAME));
							record.put(p);
							record.put(q);
							record.put(t);
							record.put(djonDBUtil.round(q*p*(1+t), 2));
							rows.put(record);
						}
						ret.put("page", page);
						ret.put("total", total_pages);
						ret.put("records", count);
						ret.put("rows", rows);
						ret.put("ret", true);
					}
				}
			}
		}
		catch (Throwable theException) 	    
		{
		     System.out.println(theException); 
		}
		finally
		{
			out.print(ret);
			out.close();
		}		
	}

}
