package cz.muni.fi.lasaris.sbms;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.StaticHttpHandler;
import org.glassfish.grizzly.ssl.SSLContextConfigurator;
import org.glassfish.grizzly.ssl.SSLEngineConfigurator;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;

import cz.muni.fi.lasaris.sbms.SBMSApplication;

import java.io.IOException;
import java.net.URI;

/**
 * Main class.
 *
 */
public class Main {

    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    
    private static SBMSApplication app;
    
    public static HttpServer startServer() {
        
    	HttpServer g = null; 
    	
    	app = SBMSApplication.getInstance();
		
		//new ResourceConfig().packages("cz.muni.fi.lasaris.sbms.api");
        
		
		// https://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-using-java-keytool.html
		// http://stackoverflow.com/questions/21098105/ssl-with-grizzly-and-jersey
		if(Boolean.parseBoolean(app.getSBMSProperties().getProperty("server.https"))) {
		SSLContextConfigurator sslCon = new SSLContextConfigurator();
	    sslCon.setKeyStoreFile(app.getSBMSProperties().getProperty("server.https.keystore.path")); // contains server keypair
	    sslCon.setKeyStoreType("JKS");
	    sslCon.setKeyStorePass(app.getSBMSProperties().getProperty("server.https.keystore.pass"));
		sslCon.setKeyPass(app.getSBMSProperties().getProperty("server.https.keystore.key"));
	   
        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        
	    g = GrizzlyHttpServerFactory.createHttpServer(URI.create(app.getURI()), app, true, 
        		new SSLEngineConfigurator(sslCon, false, false, false));
		} else {
			g = GrizzlyHttpServerFactory.createHttpServer(URI.create(app.getURI()), app);
		}
        StaticHttpHandler staticHttpHandler = new StaticHttpHandler(app.getSBMSProperties().getProperty("server.client.path"));
        staticHttpHandler.setFileCacheEnabled(false);
        g.getServerConfiguration().addHttpHandler(staticHttpHandler, app.getSBMSProperties().getProperty("server.client.uri"));
        return g;
    }

    /**
     * Main method.
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        final HttpServer server = startServer();
        System.out.println(String.format("Jersey app started with WADL available at "
                + "%sapplication.wadl\nHit enter to stop it...", app.getURI()));
        System.in.read();
        app.close();
        server.shutdownNow();
    }
}

