package server;

import remifc.PlayerFinder;
import remifc.PlayerLocation;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.server.UnicastRemoteObject;

public class PlayerFinderImpl
	extends UnicastRemoteObject
	implements PlayerFinder {
	PlayerLocation firstPlayer;
	PlayerLocation secondPlayer;

	public PlayerFinderImpl() throws RemoteException {
		super();
		firstPlayer = null;
		secondPlayer = null;
	}

	public synchronized PlayerLocation getOpponent(PlayerLocation me) {
		PlayerLocation result = null;

		try {
			if (firstPlayer == null) {
				System.out.print("" + me + "  versus  ");
				firstPlayer = me;
				while (secondPlayer == null) {
					wait();
				}
				result = secondPlayer;
				secondPlayer = null;
				notifyAll();
			} else {
				System.out.println("" + me);
				secondPlayer = me;
				notifyAll();
				while (secondPlayer == me) {
					wait();
				}
				result = firstPlayer;
				firstPlayer = null;
			}
		} catch (InterruptedException ie) {
			System.err.println("Interrupted\n");
			System.exit(1);
		}

		return result;
	}

	public static void main(String args[]) {
		try {
			PlayerFinderImpl s = new PlayerFinderImpl();

			System.setSecurityManager(new RMISecurityManager());

			Naming.rebind(PlayerFinder.NAME, s);
			System.out.println(NAME + " server running");
		} catch (Exception e) {
			System.out.println("Failed: " + e);
			e.printStackTrace();
		}
	}
}
