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

public class Exec12_32Server extends UnicastRemoteObject implements ChatServer {
  public Exec12_32Server() throws RemoteException {
    super();
  }

  /**
   * Register the client
   */
  public void register(ChatClient client) throws RemoteException {
    newID++;
    clients.add(client);
    client.setClientID(newID);
    System.out.println("Register for client"+newID);
  }

  /**
   * Unregister the client
   */
  public void unregister(ChatClient client) throws RemoteException {
    int clientID=client.getClientID();

    Iterator iter=clients.iterator();
    while (iter.hasNext()) {
      ChatClient c=(ChatClient) iter.next();
      if (c.getClientID()==clientID) {
        clients.remove(c);
        break;
      }
    }

    System.out.println("Unregisterd for client"+clientID);
  }

  /**
   * Receive the message from client and send it to all the clients
   */
  public void sendMessage(ChatClient client, String message) throws RemoteException {
    int clientID=client.getClientID();

    message="Client "+clientID+": "+message;

    Iterator iter=clients.iterator();
    while (iter.hasNext()) {
      ChatClient c=(ChatClient) iter.next();
      c.showMessage(message);
    }
  }

  public static void main(String[] args) {
    System.setSecurityManager(null);
    try {
      Exec12_32Server obj=new Exec12_32Server();
      Naming.rebind("ChatServer", obj);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  protected static List clients=new LinkedList();
  protected static int newID=0;
}

