/**
 * @author Dr. Haiping Xu
 * Created at the CIS Department, UMass Dartmouth
 */

import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.net.*;

public class BBSServer extends UnicastRemoteObject implements BBSInterface {
    private int serverPort;
    private String serverAddress;
    private Registry registry;    // rmi registry for lookup the remote objects.

    // we assume the BBS can only store one message that consists of two words
    private String word1 = "", word2 = ""; // the "BBS message"


    // This method is called from the remote BBS client.
    // This is the implementation of the BBSInterface.
    synchronized public String read() throws RemoteException {
        return word1 + " " + word2;
    }

    synchronized public void write(String w1, String w2) throws RemoteException {
        word1 = w1;
        try { Thread.sleep(random(5000)) ; } catch (InterruptedException e) { } ;
        word2 = w2;
        try { Thread.sleep(random(5000)) ; } catch (InterruptedException e) { } ;
        System.out.println("-> new BBS message is: " + word1 + " " + word2);
    }

    public BBSServer() throws RemoteException {

        try {
            // get the address of this host.
            serverAddress= (InetAddress.getLocalHost()).toString();

        } catch(Exception e){
            throw new RemoteException("can't get inet address.");
        }

        serverPort=8686;  // server port (registry's port)
        System.out.println("Server address: " + serverAddress+", port:" + serverPort);

        try {
            // create the registry and bind the name and object.
            registry = LocateRegistry.createRegistry(serverPort);
            registry.rebind("BBSServer", this);
        } catch(RemoteException e){
            throw e;
        }
    }

    private int random(int n) {
             return (int) Math.round(n * Math.random() - 0.5);
    }


    public static void main(String args[]) {
        try {
            BBSServer bbs = new BBSServer();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}