package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import server.match.Match;

public class Server {
	private ArrayList<NetworkUser> matchMakingUsers;

	public Server(final int port) {
		matchMakingUsers = new ArrayList<NetworkUser>();

		Thread clientconnect = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ServerSocket server = new ServerSocket(port);
					while (true) {
						try {
							Socket client = server.accept();

							matchMakingUsers.add(new NetworkUser(client));

							// Check if all users in the matchMakingList are
							// still connected
							// Iterator<NetworkUser> i =
							// matchMakingUsers.iterator();
							// while(i.hasNext()){
							// if(!i.next().checkConnection()){
							// i.remove();
							// System.out.println("Someone dissconected :(");
							//
							// }
							// }
							//
							// Check if there are enough players to make a match
							if (matchMakingUsers.size() >= 2) {
								new Thread(new Match(matchMakingUsers.get(0), matchMakingUsers.get(1)));
								matchMakingUsers.remove(1);
								matchMakingUsers.remove(0);
							}
							System.out.println(matchMakingUsers.size());
							System.out.println("New client connected: " + client.getRemoteSocketAddress());
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		clientconnect.start();
	}
}