package com.github.aureliano.achmed.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import com.github.aureliano.achmed.common.exception.AchmedException;
import com.github.aureliano.achmed.server.service.IService;
import com.github.aureliano.achmed.server.service.ServiceFactory;
import com.github.aureliano.achmed.server.service.ServiceType;

public class ThreadHandler implements Runnable {
	
	private static final String SERVICE_PATTERN = "^service:\\s*";
	private static final String SERVICE_NAME_PATTERN = SERVICE_PATTERN + "(read_file)$";
	
	private Socket socket;
	
	public ThreadHandler(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		IService service = this.createService();
		service.consume(this.socket);
	}
	
	private IService createService() {
		ServiceType type = this.getServiceType();
		return ServiceFactory.createService(type);
	}
	
	private ServiceType getServiceType() {
		String serviceName = this.getRequestedService();
		try {
			return ServiceType.valueOf(serviceName);
		} catch (Exception ex) {
			throw new AchmedException("There is not a service named " + serviceName);
		}
	}
	
	private String getRequestedService() {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			String requestedService = reader.readLine();
		
			if (!requestedService.matches(SERVICE_NAME_PATTERN)) {
				throw new AchmedException("Broken service name description.");
			}
			
			String serviceName = requestedService.replaceFirst(SERVICE_PATTERN, "").trim();
			return serviceName.toUpperCase();
		} catch (IOException ex) {
			throw new AchmedException(ex);
		}
	}
}
@@ -154,16 +154,49 @@
 .Socket;
+%0Aimport java.util.logging.Logger;
 %0A%0Aimport
@@ -254,24 +254,90 @@
 dException;%0A
+import com.github.aureliano.achmed.common.logging.LoggingFactory;%0A
 import com.g
@@ -715,16 +715,104 @@
 ile)$%22;%0A
+%09private static final Logger logger = LoggingFactory.createLogger(ThreadHandler.class);%0A
 %09%0A%09priva
@@ -833,21 +833,22 @@
 et;%0A%09%0A%09p
-ublic
+rivate
  ThreadH
@@ -900,16 +900,193 @@
 t;%0A%09%7D%0A%09%0A
+%09public static Runnable handle(Socket socket) %7B%0A%09%09logger.info(%22Accepted connection from: %22 + socket.getInetAddress().getHostAddress());%0A%09%09return new ThreadHandler(socket);%0A%09%7D%0A%09%0A
 %09@Overri
@@ -1269,16 +1269,61 @@
 Type();%0A
+%09%09logger.info(%22Accessing service: %22 + type);%0A
 %09%09return

Add method to handle connection.