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

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

  /**
   * Register the client, only response for two clients
   */
  public void register(ChatClient client) throws RemoteException {
    if (client1==null) {
      System.out.println("Register for client1");
      client1=client;
      client1.setClientID(1);
    }
    else if (client2==null) {
      System.out.println("Register for client2");
      client2=client;
      client2.setClientID(2);
    }
  }

  /**
   * Unregister the client
   */
  public void unregister(ChatClient client) throws RemoteException {
    if (client.getClientID()==1) {
      System.out.println("Unregister for client1");
      client1=null;
    }
    else if (client.getClientID()==2) {
      System.out.println("Unregister for client2");
      client2=null;
    }
  }

  /**
   * Receive the message from client and send it to all the clients
   */
  public void sendMessage(ChatClient client, String message) throws RemoteException {
    if (client.getClientID()==1) {
      message="Client 1: "+message;
    }
    else if (client.getClientID()==2) {
      message="Client 2: "+message;
    }

    if (client1!=null) {
      client1.showMessage(message);
    }

    if (client2!=null) {
      client2.showMessage(message);
    }
  }

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

  public static ChatClient client1=null;
  public static ChatClient client2=null;
}

