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

public class IrcServerImpl extends UnicastRemoteObject
                       implements IrcServer {
  static final int size= 10;
  String[] buff= new String[size];
  int serial= 0;

  public IrcServerImpl() throws RemoteException {
  }

  // Memoriza hasta 10 mensajes.  Si un cliente se atrasa más de size
  // mensajes, recibe mensajes nulos.
  public synchronized void put(String text) throws RemoteException {
    buff[serial%size]= text;
    System.out.println(serial+": "+text);
    serial++;
    notifyAll();
  }

  public synchronized String get(int serial) throws RemoteException {
    try {
      while (this.serial<=serial)
        wait();
      if (this.serial-serial>size)
        return null; // mensaje perdido
      else
        return buff[serial%size];
    }
    catch (InterruptedException e) {
      System.out.println("Interrupted exception");
      return null;
    }
  }

  public synchronized int getSerial() throws RemoteException {
    System.out.println("got serial id "+serial);
    return serial;
  }

  public static void main(String[] args) throws Exception {
    // Solo se necesita cuando se recuperan las clases a traves de la red
    // if (System.getSecurityManager() == null)
    //   System.setSecurityManager(new RMISecurityManager());

    String url= args.length==0 ? "IrcServer" : "//"+args[0]+"/IrcServer";
    Naming.rebind(url, new IrcServerImpl());
    System.out.println(url+" registered");
  }
}
