package sk.ondrejhirjak.web;

import org.apache.log4j.Logger;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import sk.ondrejhirjak.module.ServerModule;
import sk.ondrejhirjak.server.Configuration;
import sk.ondrejhirjak.web.exception.PersistenceExceptionMapper;

import java.net.URI;
import java.util.Set;


public class WebServer implements ServerModule {

    private static final Logger LOGGER = Logger.getLogger(WebServer.class);

    private String baseUri;

    private Set<Class<?>> classes;

    private HttpServer server;


    @Override
    public void init(Configuration configuration) {
        baseUri = "http://" + configuration.webHost + ":" + configuration.webPort + "/";
    }


    @Override
    public void start() {
        // TODO hiro: Log grizzly to log file

        final ResourceConfig rc = new ResourceConfig();
        rc.registerClasses(JacksonFeature.class);
        rc.registerClasses(PersistenceExceptionMapper.class);

        if (classes != null) {
            rc.registerClasses(classes);
        }

        server = GrizzlyHttpServerFactory.createHttpServer(URI.create(baseUri), rc);

        LOGGER.debug(String.format("Jersey app started with WADL available at %sapplication.wadl", baseUri));
    }


    @Override
    public void stop() {
        server.shutdownNow();

        // TODO hiro: Wait for server to shutdown
    }


    public String getBaseUri() {
        return baseUri;
    }


    public void setClasses(Set<Class<?>> classes) {
        this.classes = classes;
    }
}

@@ -461,16 +461,42 @@
 et.URI;%0A
+import java.util.HashSet;%0A
 import j
@@ -700,16 +700,34 @@
  classes
+ = new HashSet%3C%3E()
 ;%0A%0A    p
@@ -1673,16 +1673,168 @@
 oid 
-setClass
+addResource(Class resourceClass) %7B%0A        // TODO: fail to add classes after initialized%0A        classes.add(resourceClass);%0A    %7D%0A%0A%0A    public void addResourc
 es(S
@@ -1842,25 +1842,33 @@
 t%3CClass%3C?%3E%3E 
-c
+resourceC
 lasses) %7B%0A  
@@ -1877,30 +1877,94 @@
     
-this.classes = classes
+// TODO: fail to add classes after initialized%0A        classes.addAll(resourceClasses)
 ;%0A  

Implement addResource(s) in WebServer