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("/NouveauBloc")
public class NouveauBloc extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public NouveauBloc() {
        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");
		
		if(u != null) {
			request.setCharacterEncoding("UTF-8");

			String contenu = request.getParameter("contenu");
			String typeStr = request.getParameter("type");
			String ordreStr = request.getParameter("ordre");
			String pageIdStr = request.getParameter("pageId");
			String metadata = request.getParameter("metadata");			

			
			int ordre = Integer.parseInt(ordreStr);
			int pageId = Integer.parseInt(pageIdStr);
			Bloc.Type type = Bloc.Type.valueOf(typeStr);
				
			int idGenere = Bloc.ajouterBloc(u.getId(), pageId, contenu, ordre, type, LocalDate.now(), metadata);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("{\"idGenere\": " + idGenere + "}");	
            
		} else {
			response.sendRedirect("/Projet/");
		}
	}
}
