package requestHandlers.mongoDB;

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 com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;

public class loginH_mongo implements RequestHandler{
	
	@Override
	public void processRequest(Object user, HttpServletRequest req,
			HttpServletResponse res, Object[] services, Object log)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		MongoClient mongoClient = MongoDBUtil.openConn();
		DB db = mongoClient.getDB(MongoDBUtil.DBNAME);
		DBCollection users = db.getCollection(MongoDBUtil.USERS_COLLECTION_NAME);
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		if(username != null && password != null)
		{
			BasicDBObject searchQuery = new BasicDBObject();
			searchQuery.put(MongoDBUtil.USER_EMAIL_FIELDNAME, username);
			searchQuery.put(MongoDBUtil.USER_PASSWORD_FIELDNAME, password);
			DBCursor cursor = users.find(searchQuery);
			if(cursor.hasNext())
			{
				BasicDBObject u = (BasicDBObject)cursor.next();
				R2UserBean userbean = new R2UserBean();
				userbean.setEmail(username);
				userbean.setPassword(password);
				userbean.setFirstName(u.getString(MongoDBUtil.USER_FNAME_FIELDNAME));
				userbean.setLastName(u.getString(MongoDBUtil.USER_LNAME_FIELDNAME));
				userbean.setDocID(u.getString(MongoDBUtil.USER_ID_FIELDNAME));
				HttpSession session = req.getSession(true);	    
		        session.setAttribute("currentSessionUser", userbean); 
		        res.sendRedirect("MainUI_Mongo.jsp"); //logged-in page  
			}
			else
			{
		    	 res.sendRedirect("InvalidLogin.jsp"); //error page 
			}
		}
		else
		{
			res.sendRedirect("InvalidLogin.jsp"); //error page 
		}
		mongoClient.close();
	}

}
