package de.verteiltearchitekturen.election;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
@WebServlet(urlPatterns = "/vote")
public class BallotBoxServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        var out = response.getWriter();
        response.setContentType("text/html");
        out.println("<html><body>");
        var action = request.getParameter("action");
        if (action != null) {
            if (action.equals("vote")) {
                var alternative = request.getParameter("alternative");
                if ((alternative == null) || alternative.equals("")) {
                    alternative = "ungültige Stimmenabgabe";
                }
                BallotBox.vote(alternative);
                out.println("<p>Ihre Stimme wurde gez&auml;hlt.</p>");
            } else if (action.equals("print")) {
                out.println("<h1>abgegebene Stimmen</h1>");
                out.println("<table border='1'>");
                out.println(
                        "<tr><th align='left'>Alternative</th><th align='right'>Stimmen</th></tr>");
                var sum = 0;
                for (var vote : BallotBox.votes()) {
                    out.println(
                            "<tr><th align='left'>" + vote.choice() + "</th>");
                    out.println(
                            "<td align='right'>" + vote.votes() + "</td></tr>");
                    sum += vote.votes();
                }
                out.println("<tr><th align='left'>Summe:</th>");
                out.println("<th align='right'>" + sum + "</th></tr>");
                out.println("</table>");
            } else {
                response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED,
                        "action-Parameter hatte den Wert '" + action
                                + "'. Erlaubte Werte sind 'vote' und 'print'");
            }
        } else {
            response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED,
                    "action-Parameter hatte keinen Wert gesetzt. Erlaubte Werte sind 'vote' und 'print'");
        }
        out.println("</body></html>");
        out.flush();
    }

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
