package servlet;

import java.io.IOException;
import DAO.QuizzDAO;
import DAO.SessionDAO;
import DAO.UtilisateurDAO;
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 metier.Quizz;
import metier.Session;
import metier.Utilisateur;

@WebServlet(name="quizz",
        urlPatterns={"/QuizzInfo"})
public class QuizzInfo extends HttpServlet {
    QuizzDAO quizzDAO = new QuizzDAO();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/Quizz.html").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Utilisateur
        UtilisateurDAO uDAO = new UtilisateurDAO();
        String email_user = req.getParameter("email_User");
        String id_User = req.getParameter("id_User");
        String id_session = req.getParameter("code_pin");

        Utilisateur u_cree_quizz = null;

        if (id_User != null && !id_User.isEmpty()) {
            int id = Integer.parseInt(id_User);
            u_cree_quizz=uDAO.findById(id);
        }else if(email_user != null && !email_user.isEmpty()){
            u_cree_quizz=uDAO.findByEmail(email_user);
        }

        if (u_cree_quizz == null) {
            resp.getWriter().println("<HTML>\n<BODY>\n" +
                    "<H1> Utilisateur non trouvable </H1>" +
                    "</BODY></HTML>");
            return ;
        }

        //Session
        SessionDAO sDAO = new SessionDAO();
        Session s_attached = null;
        s_attached=sDAO.findById(Integer.parseInt(id_session));

        if(s_attached==null){
            resp.getWriter().println("<HTML>\n<BODY>\n" +
                    "<H1> Session non trouvable </H1>" +
                    "</BODY></HTML>");
            return ;
        }

        Quizz quizz = new Quizz();
        quizz.setUtilisateur(u_cree_quizz);
        quizz.setSession(s_attached);
        quizzDAO.create(quizz);
    }
}
