package ru.yandex.qe.dispenser.ws.health;

import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import ru.yandex.qe.dispenser.domain.health.HealthCheck;
import ru.yandex.qe.dispenser.domain.health.HealthChecks;

@WebServlet( name = "PingServlet",
        urlPatterns = {"/ping"},
        loadOnStartup = 1)
public class PingServlet extends HttpServlet {

    private HealthChecks healthChecks;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, HealthCheck.Result> map = healthChecks.runHealthChecks();
        Set<String> failedChecks = new HashSet<>();
        map.forEach((key, value) -> {
            if (!value.isHealthy()) {
                failedChecks.add(key);
            }
        });
        String reply = failedChecks.isEmpty()
                ? "0;OK" : "2;Critical: " + failedChecks.stream().sorted().collect(Collectors.toList());
        resp.setContentType("text/plain");
        // Always ok, for compatibility
        resp.setStatus(HttpServletResponse.SC_OK);
        try (Writer writer = resp.getWriter()) {
            writer.write(reply);
        }
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        ServletContext servletContext = config.getServletContext();
        WebApplicationContext webApplicationContext = WebApplicationContextUtils
                .getWebApplicationContext(servletContext);
        healthChecks = webApplicationContext.getBean(HealthChecks.class);
    }

}
