package fi.csc.chipster.filebroker;

import java.io.File;
import java.net.URI;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AllowSymLinkAliasChecker;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import fi.csc.chipster.auth.AuthenticationClient;
import fi.csc.chipster.rest.CORSServletFilter;
import fi.csc.chipster.rest.Config;
import fi.csc.chipster.rest.exception.ExceptionServletFilter;
import fi.csc.chipster.rest.token.TokenRequestFilter;
import fi.csc.chipster.rest.token.TokenServletFilter;
import fi.csc.chipster.rest.websocket.WebSocketClient.WebSocketClosedException;
import fi.csc.chipster.rest.websocket.WebSocketClient.WebSocketErrorException;
import fi.csc.chipster.servicelocator.ServiceLocatorClient;
import fi.csc.chipster.sessiondb.SessionDb;
import fi.csc.chipster.sessiondb.SessionDbClient;


public class FileBroker {
	
	private Logger logger = LogManager.getLogger();
	
	private AuthenticationClient authService;
	private ServiceLocatorClient serviceLocator;
	private Config config;
	@SuppressWarnings("unused")
	private String serviceId;
	
	private SessionDbClient sessionDbClient;

	private Server server;

	public FileBroker(Config config) {
		this.config = config;
	}

    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     * @throws Exception 
     * @throws InterruptedException 
     * @throws WebSocketClosedException 
     * @throws WebSocketErrorException 
     */
    public void startServer() throws Exception {
    	
    	String username = Config.USERNAME_FILE_BROKER;
    	String password = config.getPassword(username);    	
    	
    	this.serviceLocator = new ServiceLocatorClient(config);
		this.authService = new AuthenticationClient(serviceLocator, username, password);
		this.sessionDbClient = new SessionDbClient(serviceLocator, authService.getCredentials());		
    	
		File storage = new File("storage");
		storage.mkdir();    
		//this.fileResource = new FileResource(storage, sessionDbClient);
		
    	
    	TokenRequestFilter tokenRequestFilter = new TokenRequestFilter(authService);
//    	        
//    	final ResourceConfig rc = RestUtils.getDefaultResourceConfig()
//        	.register(fileResource)
//        	//.register(new LoggingFilter())
//        	.register(tokenRequestFilter);
//
//        // create and start a new instance of grizzly http server
//        // exposing the Jersey application at BASE_URI
    	URI baseUri = URI.create(this.config.getString("file-broker-bind"));
//        this.httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, rc);
    	
//    	ResourceConfig config = new ResourceConfig(FileResource.class);
//    	server = JettyHttpContainerFactory.createServer(baseUri, config);

                
    	server = new Server();
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(baseUri.getPort());
        connector.setHost(baseUri.getHost());
        server.addConnector(connector);
		
		ServletContextHandler contextHandler = new ServletContextHandler(server, "/", false, false);
		// file-root and some public files are symlinks
		contextHandler.addAliasCheck(new AllowSymLinkAliasChecker());
		contextHandler.setResourceBase(storage.getPath());
				
		FileServlet fileServlet = new FileServlet(storage, sessionDbClient);
		contextHandler.addServlet(new ServletHolder(fileServlet), "/*");
		contextHandler.addFilter(new FilterHolder(new ExceptionServletFilter()), "/*", null);
		contextHandler.addFilter(new FilterHolder(new TokenServletFilter(tokenRequestFilter)), "/*", null);
		contextHandler.addFilter(new FilterHolder(new CORSServletFilter()), "/*", null);
		
		sessionDbClient.subscribe(SessionDb.FILES_TOPIC, fileServlet, "file-broker-file-listener");
               
        server.start();
        //server.join();
    }

    /**
     * Main method.
     * @param args
     * @throws Exception 
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws Exception {
    	
//        final FileBroker server = new FileBroker(new Config());
//        server.startServer();
//        RestUtils.waitForShutdown("file-broker", server.getHttpServer());
        
        new FileBroker(new Config()).startServer();
    }

//	private HttpServer getHttpServer() {
//		return this.httpServer;
//	}

	public void close() {
		//RestUtils.shutdown("file-broker", httpServer);
		try {
			server.stop();
		} catch (Exception e) {
			logger.warn("failed to stop the file brokers", e);
		}
	}
}


@@ -771,167 +771,8 @@
 er;%0A
-import fi.csc.chipster.rest.websocket.WebSocketClient.WebSocketClosedException;%0Aimport fi.csc.chipster.rest.websocket.WebSocketClient.WebSocketErrorException;%0A
 impo
@@ -1327,23 +1327,17 @@
  Starts 
-Grizzly
+a
  HTTP se
@@ -1354,14 +1354,16 @@
 ing 
-JAX-RS
+the REST
  res
@@ -1417,28 +1417,8 @@
 urn 
-Grizzly HTTP server.
 %0A   
@@ -1443,125 +1443,8 @@
 ion 
-%0A     * @throws InterruptedException %0A     * @throws WebSocketClosedException %0A     * @throws WebSocketErrorException
  %0A  
@@ -1929,79 +1929,8 @@
    %0A
-%09%09//this.fileResource = new FileResource(storage, sessionDbClient);%0A%09%09%0A
     
@@ -2017,651 +2017,82 @@
 e);%0A
-//    %09        %0A//    %09final ResourceConfig rc = RestUtils.getDefaultResourceConfig()%0A//        %09.register(fileResource)%0A//        %09//.register(new LoggingFilter())%0A//        %09.register(tokenRequestFilter);%0A//%0A//        // create and start a new instance of grizzly http server%0A//        // exposing the Jersey application at BASE_URI%0A    %09URI baseUri = URI.create(this.config.getString(%22file-broker-bind%22));%0A//        this.httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, rc);%0A    %09%0A//    %09ResourceConfig config = new ResourceConfig(FileResource.class);%0A//    %09server = JettyHttpContainerFactory.createServer(baseUri, config);%0A
+%0A    %09URI baseUri = URI.create(this.config.getString(%22file-broker-bind%22));
 %0A   
@@ -3152,33 +3152,8 @@
 ();%0A
-        //server.join();%0A
     
@@ -3345,43 +3345,15 @@
   %09%0A
-//
        
- final FileBroker server =
  new
@@ -3381,26 +3381,8 @@
 g())
-;%0A//        server
 .sta
@@ -3397,299 +3397,37 @@
 ();%0A
-// 
     
-   RestUtils.waitForShutdown(%22file-broker%22, server.getHttpServer());%0A        %0A        new FileBroker(new Config()).startServer();%0A    %7D%0A%0A//%09private HttpServer getHttpServer() %7B%0A//%09%09return this.httpServer;%0A//%09%7D%0A%0A%09public void close() %7B%0A%09%09//RestUtils.shutdown(%22file-broker%22, httpServer);
+%7D%0A%0A%09public void close() %7B
 %0A%09%09t

Remove old code