//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package de.ugoe.cs.autoquest.htmlmonitor;

import java.util.EnumSet;

import javax.servlet.DispatcherType;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlets.CrossOriginFilter;

import de.ugoe.cs.util.console.Console;

/**
 * <p>
 * this is the web server, that receives the client messages. It also provides the java script
 * that is used by the client via the URL /script/autoquest-htmlmonitor.js. It is initialized
 * with a port on which it shall listen, as well as a message listener to forward the received
 * messages to. Internally it starts a jetty web server with a single {@link HtmlMonitorServlet}
 * to receive the messages as well as a .
 * </p>
 * 
 * @author Patrick Harms
 */
class HtmlMonitorServer implements HtmlMonitorComponent {
    
    /**
     * the port to listen on
     */
    private int port;

    /**
     * the jetty web server used for receiving messages
     */
    private Server server;

    /**
     * the message listener to forward the messages to
     */
    private HtmlMonitorMessageListener messageListener;

    /**
     * <p>
     * initializes the server with the port to listen on and the message listener to forward
     * the messages to.
     * </p>
     *
     * @param port            the port to listen on
     * @param messageListener the message listener to forward the messages to
     */
    HtmlMonitorServer(int port, HtmlMonitorMessageListener messageListener) {
        this.port = port;
        this.messageListener = messageListener;
    }

    /* (non-Javadoc)
     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#init()
     */
    @Override
    public synchronized void init() {
        if (server != null) {
            throw new IllegalStateException("already initialized. First call stop()");
        }

        server = new Server(port);
        
        /*
        // the following code can be used to support SSL directly
        server = new Server();
        
        SslSocketConnector connector = new SslSocketConnector();
        connector.setPort(port);
        connector.setKeystore("data/keystore");
        connector.setPassword("123456");
        connector.setKeyPassword("123456");
        connector.setTruststore("data/keystore");
        connector.setTrustPassword("123456");
        server.addConnector(connector);*/

        ServletContextHandler root =
            new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);

        HtmlMonitorServlet servlet = new HtmlMonitorServlet(messageListener);
        ServletHolder servletHolder = new ServletHolder(servlet);
        root.addServlet(servletHolder, "/*");
        
        CrossOriginFilter filter = new CrossOriginFilter();
        FilterHolder filterHolder = new FilterHolder(filter);
        filterHolder.setInitParameter("allowedOrigins", "*");
        filterHolder.setInitParameter("allowedMethods", "GET,POST");
        root.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class));
    }

    /* (non-Javadoc)
     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#start()
     */
    @Override
    public synchronized void start() throws HtmlMonitorException {
        if (server == null) {
            throw new IllegalStateException("server not initialized yet. First call init()");
        }
        
        try {
            server.start();
        }
        catch (Exception e) {
            throw new HtmlMonitorException("could not start server", e);
        }
    }


    /* (non-Javadoc)
     * @see de.ugoe.cs.autoquest.htmlmonitor.HtmlMonitorComponent#stop()
     */
    @Override
    public synchronized void stop() {
        try {
            if (server != null) {
                server.stop();
            }
        }
        catch (Exception e) {
            Console.printerrln("could not stop HTML monitor server: " + e.getMessage());
            Console.logException(e);
        }
    }

}
