package vs;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class WahlenController
 */
@WebServlet(name = "ControllerWahlen", description = "Controller für die Wahlen Web-Anwendung", urlPatterns = { "/do",
        "/wahlservlet" })
public class WahlenController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Map<String, Integer> poll = new HashMap<>();

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String choice = request.getParameter("choice");
        if (choice != null) {
            if (!this.poll.containsKey(choice)) {
                this.poll.put(choice, 0);
            }
            this.poll.put(choice, this.poll.get(choice) + 1);
            response.getOutputStream()
                    .println("<html><body><h1>Wahlergebnisse</h1><p>Stimme ist gezählt</body></html>");
        } else {
            String action = request.getParameter("action");
            if (action != null && action.equals("ergebnis")) {
                response.getOutputStream().println("<html><body><h1>Wahlergebnisse</h1><ul>");
                for (var c : poll.keySet()) {
                    response.getOutputStream().println("<li>" + c + ": " + poll.get(c) + "</li>");
                }
                response.getOutputStream().println("</ul></body></html>");
            } else {
                response.sendError(jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST);
            }
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}
