package projet;

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.time.LocalDate;

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

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Utilisateur u = (Utilisateur) session.getAttribute("utilisateur");
		
		if(u != null) {
			response.sendRedirect("AfficherPage");
		}else {
			response.sendRedirect("/Projet/");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    HttpSession session = request.getSession();
	    Utilisateur u = (Utilisateur) session.getAttribute("utilisateur");

	    response.setContentType("application/json");
	    response.setCharacterEncoding("UTF-8");

	    if(u != null) {
	        request.setCharacterEncoding("UTF-8");

	        String titre = request.getParameter("titre");
	        String pageIdStr = request.getParameter("pageId");

	        if (titre == null || titre.trim().isEmpty()) {
	            response.getWriter().write("{\"error\": \"Titre vide\"}");
	        } else {
	        	int pageId = Integer.parseInt(pageIdStr);
	            int id = Page.ajouterPage(u.getId(), titre, LocalDate.now(), pageId);
	            if (id != -1) {
	                response.getWriter().write("{\"id\": " + id + "," + "\"pageId\": " + pageId + "}");
	            } else {
	                response.getWriter().write("{\"error\": \"Erreur de création\"}");
	            }
	        }
	    } else {
	        response.getWriter().write("{\"error\": \"Utilisateur non connecté\"}");
	    }
	}
}
