package de.ugoe.cs.autoquest.htmlmonitor;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;

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

/**
 * TODO: comment
 * 
 * @author Patrick Harms
 */
class HtmlMonitorServer implements HtmlMonitorComponent {
    
    /**
     * 
     */
    private int port;

    /**
     * 
     */
    private Server server;

    /**
     * 
     */
    private HtmlMonitorMessageListener messageListener;

    /**
     * <p>
     * TODO: comment
     * </p>
     *
     */
    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);
        Context root = new Context(server, "/", Context.SESSIONS);

        HtmlMonitorServlet servlet = new HtmlMonitorServlet(messageListener);
        ServletHolder servletHolder = new ServletHolder(servlet);
        root.addServlet(servletHolder, "/*");
    }

    /* (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);
        }
    }

}
