import java.rmi.*;
import java.rmi.server.*; 
import java.rmi.registry.*; 
import java.util.*;

public class Server extends UnicastRemoteObject implements ServerExports {

    ClientExports[] clients = new ClientExports[100]; 

    Penguin[] players = new Penguin[100];
    int size = -1; 
    public Server() throws RemoteException {
	System.out.println("Server being initialized... "); 
    }
    
    public int register(ClientExports there) throws RemoteException {

	System.out.println("I need to register a client: " + there); 

	size ++; 

	System.out.println(size + ", " + clients.length); 

	int i = size; 

	try { 

	    clients[i] = there; 
	    
	    System.out.println("Client " + i + " has registered."); 
	    
	    System.out.println("I have registered: " + i); 

	} catch (Exception e) { System.out.println("Darn: " + e); } 

	return i; 
	
    }
    
    public void broadcast(int id, 
			  int x, int y, // actual location (pixels) 
			  String action) throws RemoteException {
	
	System.out.println("Client " + id + " is broadcasting."); 
	
	if (players[id] == null) {
	    
	    players[id] = new Penguin(x, y, 30, 30, "(server, " + id + ")"); 
	    
	    for (int i = 0; i <= size; i++) {
		for (int j = 0; j <= size; j++) {
		    clients[i].update(j, players[j].x, players[j].y, action); 
		}
	    }
	    
	} else { 
	    
            // players[id].moveTo(x, y); 
	    
	    for (int i = 0; i <= size; i++) {
		
		clients[i].update(id, x, y, action); 
		
	    }
	    
	}
	
    }
    
    public static void main(String[] args) {
	System.setSecurityManager(new RMISecurityManager()); 
	try {
	    
	    Server pam = new Server(); 
	    Registry cat = 
		LocateRegistry.createRegistry(Integer.parseInt(args[0])); 
	    cat.bind("Dirac", pam); 
	    System.out.println("Server is ready... "); 
	    
	} catch (Exception e) {
	    System.out.println("Server error: " + e + "... "); 
	}
    }
     
}

