/*
 * Copyright (c) 2000, 2001, 2002 The University of Utah and the Flux Group.
 * All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this file
 * for any purpose with or without restriction is hereby granted.
 */

import edu.utah.janosvm.sys.Team;
import edu.utah.janosvm.sys.TeamHandle;
import edu.utah.janosvm.sys.Exportable;
import edu.utah.janosvm.sys.Importable;
import edu.utah.janosvm.sys.DeadTeamException;
import edu.utah.janosvm.sys.NoSuchExportException;
import edu.utah.janosvm.sys.TeamEjectionException;

public class HelloHandle
    /*
     * Subclass from Importable since we're going to import an object
     * from the kernel which does the real work.
     */
    extends Importable
{
    private HelloBackEnd be;

    protected void bindTo(Exportable ex)
    {
	/*
	 * When importObject is called below it will eventually call this
	 * function with the object to be imported.  This allows us to store
	 * the object in a properly typed field as well as giving us a chance
	 * to make any other bindings between the two objects.
	 */
	this.be = (HelloBackEnd)ex;
    }

    protected void unbindFrom()
    {
	/*
	 * When an import or export is revoked this function will be called
	 * to cut any connections between the two objects.
	 */
	this.be = null;
    }
    
    public HelloHandle()
	throws DeadTeamException, TeamEjectionException, NoSuchExportException
    {
	Team team = Team.current();

	/* Import the RemoteHello object exported from the kernel */
	team.getKernelTeam().importObject(this, "HelloServer");
    }

    /*
     * Client interface for the corresponding server method.
     *
     * Note that this method needs to be synchronized since the imported
     * pointer is only valid as long as the object is locked.
     */
    public synchronized void sayHelloTo(String name)
    {
	if( this.be != null )
	{
	    /* We have a valid server object, call its method */
	    be.sayHelloTo(name);
	}
	else
	{
	    /* The server object was revoked */
	    System.err.println("Lost server object");
	}
    }
    
    public static void main(String args[])
	throws Exception
    {
	/* Create an interface to the kernel printer object */
	HelloHandle hh = new HelloHandle();

	/* Output something with our new client */
	if( args.length == 0 )
	{
	    hh.sayHelloTo("World");
	}
	else
	{
	    int lpc;

	    for( lpc = 0; lpc < args.length; lpc++ )
	    {
		hh.sayHelloTo(args[lpc]);
	    }
	}
    }
	
}
