package no.valg.valgnatt.frontend;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Servlet'en mottar innkommende meldinger fra Backend-server (statussjekk og rapportoppdateringer). Servlet'en har også ansvaret
 * for å initialisere Frontend til en slags "null-tilstand" ved oppstart.
 */
public class MottakFraBackendServlet extends HttpServlet {

	private static final Logger LOG = LogManager.getLogger(MottakFraBackendServlet.class);
	private static final String STATUS = "status";

	private static Kontroller kontroller;

	@Override
	public void init() throws ServletException {
		synchronized (this) {
			kontroller = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()).getBean(Kontroller.class);
			try {
				kontroller.setStatusVedOppstart();
				kontroller.initialiser();
			} catch (IOException e) {
				throw new ServletException(e);
			}
		}
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		try {
			StringBuilder sb = new StringBuilder();
			BufferedReader br = req.getReader();
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line).append('\n');
			}
			br.close();

			String reply;
			if (sb.toString().startsWith(STATUS)) {
				reply = kontroller.prosesserStatus(sb.toString());
			} else {
				reply = kontroller.prosesserRapporterFraBackend(sb.toString());
			}

			res.setContentType("text/plain");
			res.getWriter().println(reply);
		} catch (Exception e) {
			LOG.error("Feil oppstod: " + e, e);
			throw new ServletException("Feil oppstod i MottakFraBackendServlet.doPost()", e);
		}
	}

}
