
// Author: Josh Holtrop
// Date: 2008-09-17
// CS656
// Lab Excersize 2

import java.util.HashMap;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

/**
 * This class implements the PresenceService interface.
 * It provides a presence service for the chat system.
 */
public class PresenceServiceImpl implements PresenceService
{
    /* A structure to store information about the currently
     * registered users */
    private HashMap<String, RegistrationInfo> myRegisteredUsers =
		new HashMap<String, RegistrationInfo>();

	public PresenceServiceImpl()
	{
		super();
	}

    /* a user calls this method to register with the presence service */
    public void register(RegistrationInfo reg)
	{
        myRegisteredUsers.put(reg.getUserName(), reg);
//		System.out.println("register(): " + reg.getUserName() + ", " + reg.getHost() + ", " + reg.getPort() + ", " + reg.getStatus());
	}

    /* a user calls this method to unregister with the presence service */
    public void unregister(String userName)
	{
	    myRegisteredUsers.remove(userName);
//		System.out.println("unregister(): " + userName);
	}

    /* a user calls this method to get the registration information
     * for another user by name */
    public RegistrationInfo lookup(String name)
	{
	    return myRegisteredUsers.get(name);
	}

    /* a user calls this method to retrieve a list of all the
     * registered users */
    public RegistrationInfo[] listRegisteredUsers()
	{
		return myRegisteredUsers.values().toArray(new RegistrationInfo[0]);
	}

    /* the main method is invoked when starting the presence service */
	public static void main(String[] args)
	{
	    int port = 1099;
	    if (args.length >= 1)
        {
            port = Integer.parseInt(args[0]);
        }

		if (System.getSecurityManager() == null)
		{
			System.setSecurityManager(new SecurityManager());
		}
		try
		{
			PresenceServiceImpl impl = new PresenceServiceImpl();
			PresenceService stub = (PresenceService)
				UnicastRemoteObject.exportObject(impl, 0);
			Registry registry = LocateRegistry.getRegistry(port);
			registry.rebind("PresenceService", stub);
			System.out.println("PresenceService bound");
		}
		catch (Exception e)
		{
			System.err.println("PresenceServiceImpl exception:");
			e.printStackTrace();
		}
	}
}


