package servlet;

import java.io.IOException;
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 DAO.*;
import metier.*;
import java.util.List;
import java.util.Arrays;

@WebServlet(name="question",
        urlPatterns={"/QuestionInfo"})
public class QuestionInfo extends HttpServlet {


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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        QuizzDAO qDAO = new QuizzDAO();
        QuestionDAO questionDAO = new QuestionDAO();
        String ennonce = req.getParameter("question");
        String type = req.getParameter("type");
        String choixPossible = req.getParameter("choixPossible");
        String reponse = req.getParameter("reponse");
        String idQuizz = req.getParameter("idQuizz");

        Question question = new Question();
        Quizz quizz = qDAO.findById(Integer.parseInt(idQuizz));
        if(quizz==null){
            resp.getWriter().println("<HTML>\n<BODY>\n" +
                    "<H1> Quizz non trouvable </H1>" +
                    "</BODY></HTML>");
            return ;
        }
        quizz.addQuestion(question);
        question.setQuestion(ennonce);
        

        List<String> listRep = Arrays.asList(reponse.split("\n"));


        if(type.equals("choix")){
            Choix choix = new Choix();
            question.setReponse(choix);
            List<String> listChoix = Arrays.asList(choixPossible.split("\n"));
            choix.setChoix(listChoix);
            choix.setReponses(listRep);
        }
        else if (type.equals("courte")){
            ReponseCourte reponseCourte = new ReponseCourte();
            question.setReponse(reponseCourte);
            reponseCourte.setReponses(listRep);
        }
        else{
           resp.getWriter().println("<HTML>\n<BODY>\n" +
                    "<H1> Type de question non trouvé </H1>" +
                    "</BODY></HTML>");
            return ; 
        }

        questionDAO.create(question);

    }
}