package ru.yandex.webmaster3.worker;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class WorkerPingInfoHandler extends AbstractHandler {
    private static final Logger log = LoggerFactory.getLogger(WorkerPingInfoHandler.class);
    private static final ObjectMapper OM = new ObjectMapper();

    private String localDCName;

    @Override
    public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
        final String servantName = target.substring(1);

        if (!"ping".equalsIgnoreCase(servantName)) {
            return;
        }
        if ("true".equals(baseRequest.getParameter("showInfo"))) {
            respondWithInfo(response);
        } else {
            respondOK(response);
        }
        baseRequest.setHandled(true);
    }

    private void respondWithInfo(HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        try (ServletOutputStream out = response.getOutputStream()) {
            ObjectNode responseJson = OM.createObjectNode();
            JsonNode localDCNode = localDCName == null ? NullNode.getInstance() : new TextNode(localDCName);
            responseJson.set("localDC", localDCNode);
            OM.writeValue(out, responseJson);
            out.flush();
        }
    }

    private void respondOK(HttpServletResponse response) throws IOException {
        try (ServletOutputStream out = response.getOutputStream()) {
            out.write("0;OK".getBytes());
            out.write(System.getProperty("line.separator").getBytes());
            out.flush();
        }
    }

    @Required
    public void setLocalDCName(String localDCName) {
        this.localDCName = localDCName;
    }
}
