package myServerTests.myServer;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.jetty.server.CustomRequestLog;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.thread.QueuedThreadPool;

import io.vavr.control.Try;
import myServerTests.myHandlers.MyRootHandler;
import myServerTests.myServlets.MyUploadServlet;
import myUtilities.MyUtilities;

public class MyServer {

	public MyServer() {

		Try.run(() -> {

			final QueuedThreadPool threadPool = new QueuedThreadPool();

			threadPool.setName(this.getClass().getName());

			final Server server = new Server(threadPool);

			{
				final ServerConnector serverConnector = new ServerConnector(server);
				serverConnector.setPort(8080);
				server.addConnector(serverConnector);
			}

			addHandlers(server);

			server.start();

		});

	}

	private void addHandlers(final Server server) {

		final List<ContextHandler> contextHandlers = new ArrayList<>();

		{
			final ContextHandler contextHandler = new ContextHandler("/");
			contextHandler.setHandler(new MyRootHandler());
			contextHandlers.add(contextHandler);
		}
		{

			final ServletContextHandler servletContextHandler = new ServletContextHandler();
			servletContextHandler.setContextPath("/" + MyContext.ServletContextHandler.value);

			contextHandlers.add(servletContextHandler);

			{

				servletContextHandler.addServlet(MyUploadServlet.class, "/" + MyContext.MyUploadServlet.value);

			}

		}
		{

			final Path path = Try.of(() -> MyUtilities.getTempFile("RequestLog", "log")).get();

			final CustomRequestLog customRequestLog = new CustomRequestLog(path.toString(),
					CustomRequestLog.EXTENDED_NCSA_FORMAT);

			server.setRequestLog(customRequestLog);

		}

		final ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection();

		contextHandlerCollection.setHandlers(contextHandlers.toArray(contextHandlers.stream().toArray(Handler[]::new)));

		server.setHandler(contextHandlerCollection);

	}

}
