package DAOs;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

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

public class R2UserDAO {
	public static R2UserBean login(final R2UserPassBean bean)
	{
		  
		
        String username = bean.getUserName();    
        String password = bean.getPassword();   
	    
        String searchQuery = "SELECT * FROM R2User WHERE Email=("
        				   + "SELECT UserName FROM R2UserPass WHERE UserName='"
        				   + username
        				   + "' AND password='"
        				   + password
        				   + "')";
        Connection con = null;
        Statement stmt = null;  
        ResultSet rs = null;
        R2UserBean userbean = new R2UserBean();;
        try 
        {
           //connect to DB 
           con = ConnectionManager.getConnection();
           stmt = con.createStatement();
           rs = stmt.executeQuery(searchQuery);	        
           boolean more = rs.next();
  	       
           // if user does not exist set the isValid variable to false
           if (!more) 
           {
              System.out.println("Sorry, you are not a registered user! Please sign up first");
              userbean.setValid(false);
           } 
  	        
           //if user exists set the isValid variable to true
           else if (more) 
           {  	     	
              System.out.println("Welcome " + rs.getString("FirstName"));
              
              userbean.setFirstName(rs.getString("FirstName"));
              userbean.setLastName(rs.getString("LastName"));
              userbean.setEmail(username);
              userbean.setUserID(rs.getInt("UserID"));
              userbean.setValid(true);
           }
        } 

        catch (Exception ex) 
        {
           System.out.println("Log In failed: An Exception has occurred! " + ex);
        }
        finally
        {
        	DBUtil.closeResultSet(rs);
        	DBUtil.closeStmt(stmt);
        	DBUtil.closeConnection(con);
        }
        return userbean;
	}
}
