package vs;

import java.io.IOException;
import java.io.PrintWriter;

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

@WebServlet("/vote")
public class BallotBoxServlet extends HttpServlet {
	/**
	 *
	 */
	private static final long serialVersionUID = 659659337839534283L;
	private BallotBox ballotBox = new BallotBox();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<html><body>");
		String action = request.getParameter("action");
		if (action != null) {
			if (action.equals("vote")) {
				String alternative = request.getParameter("alternative");
				if ((alternative == null) || alternative.equals("")) {
					alternative = "ungültige Stimmenabgabe";
				}
				this.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>");
				for (String alternative : this.ballotBox.getChoices()) {
					out.println("<tr><th align='left'>" + alternative + "</th>");
					out.println("<td align='right'>" + this.ballotBox.getNumberOfVotes(alternative) + "</td></tr>");
				}
				out.println("<tr><th align='left'>Summe:</th>");
				out.println("<th align='right'>" + this.ballotBox.countVotes() + "</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);
	}
}
