package com.github.versatilevelociraptor.safevelociraptorserver;

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


public class Server {
	public static final int PORT = 8005;
	private ServerSocket serverSocket;
	private Controller controller;
	private RobotController roboController;
	public static final int MAX_CLIENTS = 2;
	public Server() {
		try {
			serverSocket = new ServerSocket(PORT);
		} catch (IOException e) {
			e.printStackTrace();
		}
		initializeConnections();
	}
	
	public void initializeConnections() {
		Socket client;
		int connectedClients = 0;
		boolean controlerConnected = false , robotControllerConnected = false;
		while(connectedClients < MAX_CLIENTS) {
			try {
				client = serverSocket.accept();
				connectedClients++;
				BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
				String ID = reader.readLine();
				if(Integer.parseInt(ID) == Controller.ID && !controlerConnected) {
					controller = new Controller(client);
					connectedClients++;
					controlerConnected = true;
				} else if(Integer.parseInt(ID) == RobotController.ID && !robotControllerConnected) {
					roboController = new RobotController(client);
					connectedClients++;
					robotControllerConnected = true;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void createCommunicationSession() {
		new Thread(new ServerThread(roboController, controller)).start();
		new Thread(new ServerThread(controller, roboController)).start();
	}

	public static void main(String[] args) {
		Server server = new Server();
		server.createCommunicationSession();
	}
	
	private class ServerThread implements Runnable{
		private Client send;
		private Client recieve;
		
		public ServerThread(Client send, Client recieve) {
			this.send = send;
			this.recieve = recieve;
		}
		
		/* (non-Javadoc)
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {
			recieve.sendCommand(send.recieveCommand());
		}	
	}
}

@@ -266,11 +266,11 @@
 T = 
-800
+258
 5;%0A%09
@@ -784,16 +784,65 @@
 %09%09try %7B%0A
+%09%09%09%09System.out.println(%22Looking for clients..%22);%0A
 %09%09%09%09clie
@@ -1129,32 +1129,78 @@
 roller(client);%0A
+%09%09%09%09%09System.out.println(%22Client Connected!%22);%0A
 %09%09%09%09%09connectedCl
@@ -1376,24 +1376,70 @@
 er(client);%0A
+%09%09%09%09%09System.out.println(%22Client Connected!%22);%0A
 %09%09%09%09%09connect
@@ -1554,16 +1554,16 @@
 );%0A%09%09%09%7D%0A
-
 %09%09%7D%0A%09%7D%0A%09
@@ -1559,24 +1559,113 @@
 %09%7D%0A%09%09%7D%0A%09%7D%0A%09%0A
+%09public void restart() %7B%0A%09%09initializeConnections();%0A%09%09createCommunicationSession();%0A%09%7D%0A%09%0A
 %09public void

Connect to server when clicking button