package com.github.aureliano.achmed.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.github.aureliano.achmed.common.StatusCode;
import com.github.aureliano.achmed.common.logging.LoggingFactory;

public class AchmedServerHandler {

	private static final Logger logger = LoggingFactory.createLogger(AchmedServerHandler.class);
	private static AchmedServerHandler instance;
	
	private Integer portNumber;
	
	private AchmedServerHandler() {}
	
	public static AchmedServerHandler instance() {
		if (instance == null) {
			instance = new AchmedServerHandler();
		}
		
		return instance;
	}
	
	public void startUp(Integer portNumber) {
		this.configurePortNumber(portNumber);
		
		try (
			ServerSocket serverSocket = new ServerSocket(portNumber);
		) {
			logger.info("Achmed server started and listening on port " + portNumber);
			
			while (true) {
				Socket clientSocket = serverSocket.accept();
				logger.info("Accepted connection from: " + clientSocket.getInetAddress().getHostAddress());
				
				clientSocket.close();
				logger.info("Closed connection.");
			}
		} catch (IOException ex) {
			logger.log(Level.SEVERE, ex.getMessage(), ex);
			System.exit(StatusCode.SERVER_LISTEN_CONNECTION.getCode());
		}
	}
	
	public void shutDown() {
		logger.info("Achmed server has just shut down.");
	}
	
	private void configurePortNumber(Integer portNumber) {
		this.portNumber = portNumber;
		if ((this.portNumber == null) || (this.portNumber <= 0)) {
			logger.log(Level.SEVERE, "Invalid port number: " + this.portNumber);
			System.exit(StatusCode.CLI_PARAMETERS_ERROR.getCode());
		}
	}
}
@@ -100,32 +100,8 @@
 et;%0A
-import java.net.Socket;%0A
 impo
@@ -919,246 +919,34 @@
 %0A%09%09%09
-%0A%09%09%09while (true) %7B%0A%09%09%09%09Socket clientSocket = serverSocket.accept();%0A%09%09%09%09logger.info(%22Accepted connection from: %22 + clientSocket.getInetAddress().getHostAddress());%0A%09%09%09%09%0A%09%09%09%09clientSocket.close();%0A%09%09%09%09logger.info(%22Closed connection.%22);%0A%09%09%09%7D
+this.listen(serverSocket);
 %0A%09%09%7D
@@ -1176,16 +1176,194 @@
 );%0A%09%7D%0A%09%0A
+%09private void listen(ServerSocket serverSocket) throws IOException %7B%0A%09%09while (true) %7B%0A%09%09%09Runnable thread = ThreadHandler.handle(serverSocket.accept());%0A%09%09%09thread.run();%0A%09%09%7D%0A%09%7D%0A%09%0A
 %09private

Handle multiple connections.