package projet;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("")
public class Accueil extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public void init() {
		ParamBD.init(getServletContext());
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Utilisateur u = (Utilisateur) session.getAttribute("utilisateur");
		
		if(u == null) {
			request.setAttribute("erreur", 0);
			RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/Accueil.jsp");
            rd.forward(request, response);
		} else {
			response.sendRedirect("AfficherPage");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String mdp = request.getParameter("mdp");
		String action = request.getParameter("action");
		
		if(action.equals("connexion")) {
			Utilisateur u = Utilisateur.authentifier(login, mdp);
			if(u != null) {
				HttpSession session = request.getSession();
				session.setAttribute("utilisateur", u);
				response.sendRedirect("AfficherPage");
			}else {
				request.setAttribute("erreur", 1);
				RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/Accueil.jsp");
				rd.forward(request, response);
			}
		} else if (action.equals("inscription")){
			Utilisateur u = Utilisateur.inscrire(login, mdp);
			if(u != null) {
				HttpSession session = request.getSession();
				session.setAttribute("utilisateur", u);
				response.sendRedirect("AfficherPage");
			}else {
				request.setAttribute("erreur", 2);
				RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/Accueil.jsp");
				rd.forward(request, response);
			}
		}
	}
}
