package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;

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

import com.artifacts.FactoryProvider;
import com.dao.UserDao;
import com.entities.User;


public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public LoginServlet() {
        super();
       
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	response.setContentType("text/html;charset=UTF-8");
    	try(PrintWriter out = response.getWriter()){
    		try {
    			
    			String email = request.getParameter("email");
    			String password = request.getParameter("password");
    			
    			UserDao userDao = new UserDao(FactoryProvider.getFactory());
    			User user =userDao.getUserByEmailAndPassword(email,password);
    			HttpSession httpSession = request.getSession();
    			
    			if (user==null) {
    				
    				httpSession.setAttribute("message","Invalid Details! Try with verified one!");
    				response.sendRedirect("login.jsp");
    				
    			}else {
    				out.println("<h1>Hello , "+user.getUserName() +"</h1>");
    				httpSession.setAttribute("current-user",user);
    				response.sendRedirect("index.jsp");
    				
    			}
    			
    			
    			
    			
    		}catch(Exception e) {
    			
    		}
    		
    	}
    		
    		
    		
    	}
    	
    	

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		processRequest(request,response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		processRequest(request, response);
	}

}
