package ru.yandex.webmaster3.monitoring.dashboard;

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.base.Charsets;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.entity.ContentType;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Oleg Bazdyrev on 14/06/2017.
 */
public class DashboardHandler extends AbstractHandler {
    private static final Logger log = LoggerFactory.getLogger(DashboardHandler.class);

    private static final Map<String, String> RESOURCES_BY_TARGET = ImmutableMap.<String, String>builder()
        .put("/dashboard.html", "dashboard.html")
        .put("/notifications.html", "notifications.html")
        .put("/periodic.html", "periodic.html")
        .put("/dataTables.cellEdit.js", "dataTables.cellEdit.js")
        .put("/dashboard.js", "dashboard.js")
        .put("/dashboard.css", "dashboard.css")
        .put("", "dashboard.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 resource, Request baseRequest, HttpServletResponse response) throws IOException {
        baseRequest.setHandled(true);
        response.setStatus(HttpServletResponse.SC_OK);
        if (resource.endsWith(".html")) {
            response.setContentType(ContentType.TEXT_HTML.getMimeType());
        } else if (resource.endsWith(".js")) {
            response.setContentType(ContentType.create(
                    "application/javascript", Consts.UTF_8).getMimeType()) ;
        } else if (resource.endsWith(".css")) {
            response.setContentType(ContentType.create(
                    "text/css", Consts.UTF_8).getMimeType());
        } else {
            response.setContentType(ContentType.TEXT_PLAIN.getMimeType());
        }
        InputStream is = getClass().getClassLoader().getResourceAsStream(resource);
        PrintWriter writer = response.getWriter();
        IOUtils.copy(is, writer, Charsets.UTF_8);
        writer.flush();
    }
}
