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;
import java.util.ArrayList;

@WebServlet("/AfficherPage")
public class AfficherPage extends HttpServlet {
	private static final long serialVersionUID = 1L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Utilisateur u = (Utilisateur) session.getAttribute("utilisateur");
		
		String idStr = request.getParameter("id");
		
		if(u != null) {
			u.chargerPages();
			u.chargerPagesPartagees();
			ArrayList<Page> listePages = u.getListePages();
			ArrayList<Page> listePagesPartagees = u.getListePagesPartagees();
			ArrayList<Message> listeMessages = Message.getListeMessages();
			ArrayList<Utilisateur> listeUtilisateurs = Utilisateur.getListeUtilisateurs();
			
			request.setAttribute("listePages", listePages);
			request.setAttribute("listePagesPartagees", listePagesPartagees);
			request.setAttribute("listeMessages", listeMessages);
			request.setAttribute("listeUtilisateurs", listeUtilisateurs);
			
			if (idStr != null ) {
				try {
					int id = Integer.parseInt(idStr);
					Page page = Page.getPageById(u.getId(), id);
					
					
					if (page != null) {
						request.setAttribute("page", page);
						request.getRequestDispatcher("/WEB-INF/AfficherPage.jsp").forward(request, response);
						return;
					} else {
						request.getRequestDispatcher("/WEB-INF/AfficherPage.jsp").forward(request, response);
						return;
					}		                
				} catch (NumberFormatException e) {
		            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "ID invalide");
		            return;
		        }
			}
			RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/AfficherPage.jsp");
			rd.forward(request, response);
		} else {
			response.sendRedirect("/Projet/");
		}		
	}

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

}
