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) {

		// Users waiting to play
		matchMakingUsers = new ArrayList<NetworkUser>();

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

							// User connects and is added to wait list
							matchMakingUsers.add(new NetworkUser(client));

							// Match first two users
							if (matchMakingUsers.size() >= 2) {
								new Thread(new Match(matchMakingUsers.get(0), matchMakingUsers.get(1)));
								matchMakingUsers.remove(1);
								matchMakingUsers.remove(0);
							}
							System.out.println("New client connected: " + client.getRemoteSocketAddress());
						} catch (IOException e) {
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		clientconnect.start();
	}
}