package ctbrec.docs;

import java.net.BindException;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ctbrec.servlet.StaticFileServlet;

public class DocServer {
    private static final transient Logger LOG = LoggerFactory.getLogger(DocServer.class);

    private static Server server = new Server();
    private static volatile boolean started = false;

    public synchronized static void start() throws Exception {
        if(started) {
            return;
        }

        started = true;
        server = new Server();

        HttpConfiguration config = new HttpConfiguration();
        config.setSendServerVersion(false);
        ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(config));
        http.setPort(5689);
        server.addConnector(http);

        ServletHandler handler = new ServletHandler();
        server.setHandler(handler);
        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[] { handler });
        server.setHandler(handlers);

        MarkdownServlet markdownServlet = new MarkdownServlet();
        ServletHolder holder = new ServletHolder(markdownServlet);
        handler.addServletWithMapping(holder, "/docs/*");

        AbstractDocServlet searchServlet = new SearchServlet();
        holder = new ServletHolder(searchServlet);
        handler.addServletWithMapping(holder, "/search/*");

        StaticFileServlet staticFileServlet = new StaticFileServlet("/html", false);
        holder = new ServletHolder(staticFileServlet);
        handler.addServletWithMapping(holder, "/static/*");


        try {
            server.start();
            server.join();
        } catch (BindException e) {
            LOG.error("Port {} is already in use", http.getPort(), e);
        }
    }
}
