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.JSONArray;
import org.json.JSONObject;

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

public class getRecordYears implements RequestHandler{
	private String sql = "SELECT DISTINCT Year(purchasedate) AS year " +
						 "FROM r2receipt " +
						 "WHERE userid=? ORDER BY year DESC";
	
	@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);
		JSONArray years = new JSONArray();
		
		try
		{
			HttpSession session = req.getSession(false);
			if(session != null)
			{
				R2UserBean userbean = (R2UserBean)session.getAttribute("currentSessionUser");
				if(userbean != null)
				{
					con = ConnectionManager.getConnection();
					int index = 1;
					stmt = con.prepareStatement(sql);
					stmt.setInt(index++, userbean.getUserID());
					System.out.println("sql = " + stmt.toString());
					rs = stmt.executeQuery();
					if(rs != null)
					{
						while(rs.next())
						{
							int y = rs.getInt("year");
							years.put(y);
						}
						ret.put("years", years);
					}
				}
			}
		}
			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();
			}
	}

}
