package requestHandlers.djonDB;

import java.io.IOException;

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

import requestHandlers.RequestHandler;
import Beans.R2UserBean;
import Util.MongoDBUtil;
import Util.djonDBUtil;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;

import djondb.BSONArrayObj;
import djondb.BSONObj;
import djondb.DjondbConnection;

public class loginH_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
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		if(username != null && password != null)
		{
			DjondbConnection c = djonDBUtil.openConn();
			if(c != null)
			{
				StringBuilder sb = new StringBuilder();
				sb.append("$'email' == '").append(username).append("' and $'password' == '").append(password).append("'");
				BSONArrayObj ret = c.find(djonDBUtil.DBNAME, djonDBUtil.USERS_COLLECTION_NAME, sb.toString());
				if(ret != null && ret.length() > 0)
				{
					HttpSession session = req.getSession(true);
					BSONObj userObj = ret.get(0);
					R2UserBean userbean = new R2UserBean();
					userbean.setEmail(username);
					userbean.setPassword(password);
					userbean.setFirstName(userObj.getString("fname"));
					userbean.setLastName(userObj.getString("lname"));
					userbean.setDocID(userObj.getString("_id"));
			        session.setAttribute("currentSessionUser", userbean); 
			        res.sendRedirect("MainUI_djon.jsp"); //logged-in page  
				}
				else
				{
					res.sendRedirect("InvalidLogin.jsp"); //error page 
				}
			}
			djonDBUtil.closeConn(c);
		}
		else
		{
			res.sendRedirect("InvalidLogin.jsp"); //error page 
		}
	}

}
