package nl.nuggit.moltest;
import nl.nuggit.moltest.model.Answer;
import nl.nuggit.moltest.model.Player;
import nl.nuggit.moltest.model.Result;
import nl.nuggit.moltest.model.Test;
import nl.nuggit.moltest.model.question.Question;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class TestServlet extends BaseServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Player player = (Player) request.getSession().getAttribute("player");
if (player == null) {
viewIndex(request, response, "Je bent niet ingelogd");
return;
}
Result result = (Result) request.getSession().getAttribute("result");
if (result == null) {
Test currentTest = DataService.findTest(DataService.currentTestId);
if (currentTest == null) {
throw new IllegalArgumentException("Er is geen test gaande");
}
result = new Result(player, currentTest);
request.getSession().setAttribute("result", result);
if (result.hasNextQuestion()) {
viewQuestion(request, response, null);
return;
}
}
Question question = result.nextQuestion();
if (question == null) {
viewWait(request, response);
return;
}
String answerText = request.getParameter("answerText");
if (!question.isValid(answerText)) {
viewQuestion(request, response, "Ongeldig antwoord");
return;
}
Answer answer = new Answer(answerText, question.getScore(answerText));
result.getAnswers().add(answer);
if (result.hasNextQuestion()) {
viewQuestion(request, response, null);
return;
}
result.stopTimer();
DataService.storeResult(result);
if (DataService.countPlayersToMakeTest() == 0) {
DataService.eliminatePlayers();
}
viewHome(request, response);
}
}