package ru.yandex.webmaster3.worker.state;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;

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

import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.IOUtils;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

/**
 * @author tsyplyaev
 */
public class WorkerStateHandler extends AbstractHandler {
    private static final Map<String, String> RESOURCES_BY_TARGET = ImmutableMap.<String, String>builder()
            .put("", "state.html")
            .put("/periodic", "periodic.html")
            .put("/queue", "queue.html")
            .put("/admin-clickhouse-tables", "admin-clickhouse-tables.html")
            .put("/block-notifications", "block_notifications.html")
            .put("/clickhouse-tables", "clickhouse-tables.html")
            .put("/notification-templates", "notification-templates.html")
            .put("/digest", "digest.html")
            .put("/experiments", "experiments.html")
            .put("/experiment-details", "experiment-details.html")
            .put("/experiment-edit", "experiment-edit.html")
            .build();

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        if (target.endsWith("/")) {
            target = target.substring(0, target.length() - 1);
        }
        String resource = RESOURCES_BY_TARGET.get(target);
        if (resource != null) {
            openPage(resource, baseRequest, response);
        }
    }

    private void openPage(String page, Request baseRequest, HttpServletResponse response) throws IOException {
        baseRequest.setHandled(true);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/html");

        InputStream is = getClass().getClassLoader().getResourceAsStream(page);
        PrintWriter writer = response.getWriter();

        IOUtils.copy(is, writer);

        writer.flush();
    }
}
