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

/**
 * Java Chat - A simple chatroom application - Callback Class.
 *
 * This is the Callback class. It listens for callbacks from
 * the server, passes new messages to the GUI, and deals with
 * usernames.
 *
 * @author Sean Handley
 * @version November, 2006
 */
public class Callback extends UnicastRemoteObject implements ICallback
{
    private static final long serialVersionUID = 3671520860342032921L;
    private IChatServer c;
    private ClientGUI gui;
    private String username;

    /**
     * Callback constructor.
     * 
     * Takes in a chat interface, gui and username as parameters and puts
     * them into class variables.
     * 
     * @param c
     * @param gui
     * @param username
     * @throws java.rmi.RemoteException
     */
    public Callback(IChatServer c, ClientGUI gui, String username) throws RemoteException
    {
        this.c = c;
        this.gui = gui;
        this.username = username;
    }
    /**
     * Callback interface method. Called by the server when a new message is ready.
     * 
     * @throws java.rmi.RemoteException
     */
    public void doCallback() throws RemoteException
    {
        try
        {
            gui.addMessage(c.getMessage());
            gui.updateUserList(c.getUsers());
        }
        catch(Exception e)
        {
            System.out.println(e.toString());
        }
    }
    /**
     * Force the client to logout. Called if the server is killed with clients still active.
     */
    public void forceLogout()
    {
        gui.setRequiresCleanExit(false);
        System.out.println("CONNECTION TERMINATED: Server is offline or no longer reachable.");
        gui.dispose();
        System.exit(0);
    }
    /**
     * Returns the username.
     * 
     * @return username
     * @throws java.rmi.RemoteException
     */
    public String getUsername()
    {
        return username;
    }
    /**
     * Sets the username.
     * 
     * @param username New user name
     * @throws java.rmi.RemoteException
     */
    public void setUsername(String username)
    {
        this.username = username;
    }
}