package com.github.noxan.aves.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.github.noxan.aves.net.Connection;
import com.github.noxan.aves.net.SocketConnection;
import com.github.noxan.aves.util.Tuple;

public class SocketServer implements Server, Runnable {
    private String host;
    private int port;

    private BlockingQueue<Tuple<Connection, Object>> dataEvents;
    private ServerHandler handler;

    private Set<Connection> connections;

    private ServerSocket server;
    private Thread serverThread;

    public SocketServer(ServerHandler handler) {
	this("0.0.0.0", 1666, handler);
    }

    public SocketServer(String host, int port, ServerHandler handler) {
	this.host = host;
	this.port = port;
	this.handler = handler;
	dataEvents = new LinkedBlockingQueue<>();
	connections = new HashSet<Connection>();
    }

    @Override
    public void start() {
	try {
	    server = new ServerSocket();
	    server.setSoTimeout(1000);
	    server.bind(new InetSocketAddress(host, port));
	    serverThread = new Thread(this);
	    serverThread.start();
	} catch (IOException e) {
	    e.printStackTrace();
	}
    }

    @Override
    public void run() {
	while (true) {
	    try {
		Socket socket = server.accept();
		Connection connection = new SocketConnection(this, socket);
		connections.add(connection);
		connection.start();
	    } catch (SocketTimeoutException e) {
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
    }

    @Override
    public String getHost() {
	return host;
    }

    @Override
    public int getPort() {
	return port;
    }

    public void offerData(Connection connection, Object data) {
	dataEvents.add(new Tuple<Connection, Object>(connection, data));
    }

    private class EventManager implements Runnable {
	@Override
	public void run() {
	    while (true) {
		Tuple<Connection, Object> event = dataEvents.poll();
		if (event != null) {
		    handler.handleData(event.getFirst(), event.getSecond());
		}
	    }
	}
    }
}

@@ -782,16 +782,85 @@
 hread;%0A%0A
+    private EventManager manager;%0A    private Thread managerThread;%0A%0A
     publ
@@ -1333,16 +1333,51 @@
 port));%0A
+%09    manager = new EventManager();%0A
 %09    ser
@@ -1433,16 +1433,86 @@
 tart();%0A
+%09    managerThread = new Thread(manager);%0A%09    managerThread.start();%0A
 %09%7D catch

create eventmanager instance in socketserver and start it as thread