package com.wiley.compbooks.brose.chapter11.event;

/**
 * Chapter 11, Event Service example client
 */

import org.omg.CosNaming.*;
import org.omg.CosEventChannelAdmin.*;
import org.omg.CosEventComm.*;
import org.omg.CORBA.Any;

import com.wiley.compbooks.brose.chapter11.office.*;
import com.wiley.compbooks.brose.chapter11.office.PrinterPackage.*;

import org.omg.PortableServer.*;

public class PrintClient
    extends PullConsumerPOA
{
    /** 
     * releases any resources, none in this case
     */
    public void disconnect_pull_consumer()
    {
    }
 
    
    /**  main  */
    static public void main  (String argv[])
    {
	EventChannel channel = null;
	ConsumerAdmin consumerAdmin;
	ProxyPullSupplier  proxyPullSupplier = null;
	PullConsumer pullConsumer;
	Printer printer = null;
	String userid = "MeMyselfAndI";

	if( argv.length > 0 )
	    userid = argv[0];

	// initialize ORB

	org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(argv, null);
	POA poa = null;

	try 
	{
	    // inititialize POA
	    poa = 
		POAHelper.narrow(orb.resolve_initial_references("RootPOA"));

	    // get naming service reference
	    NamingContextExt nc = 
		NamingContextExtHelper.narrow(orb.resolve_initial_references("NameService"));	

	    // find the event channel reference and the Printer
	    channel = 
		EventChannelHelper.narrow(nc.resolve(nc.to_name("office_event.channel")));

	    printer = PrinterHelper.narrow( nc.resolve(nc.to_name("Printer")));

	    poa.the_POAManager().activate();

	    // create and implicitly activate the client 
	    pullConsumer = 
		(org.omg.CosEventComm.PullConsumer)new PrintClient()._this(orb);
	    
	    // get the admin interface and the supplier proxy
	    consumerAdmin  = channel.for_consumers();
	    proxyPullSupplier = consumerAdmin.obtain_pull_supplier();
	    
	    // connect ourselves to the event channel
	    proxyPullSupplier.connect_pull_consumer( pullConsumer );
	} 
	catch (Exception e) 
	{
	    e.printStackTrace();
	    System.exit(1);
	}	  

	// print a couple of jobs

	for( int i = 0; i < 5; i++ )
	{
	    try
	    {
		System.out.println("Sending job, ID #" + 
				   printer.print("A test job", userid));
	    }
	    catch( OffLine ol )
	    {
		System.err.println("Printer found off line when printing job.");
	    }
	}

	// wait a sec...
	
	try
	{
	    System.out.println("Sleep...");
	    Thread.sleep(7000);
	}
	catch( Exception e)
	{}

	// try to cancel the last job

	int job = 4;
	try
	{
	    System.out.println("Cancelling job ID #" + job );
	    printer.cancel( job, userid );
	}
	catch( UnknownJobID ol )
	{
	    System.err.println("Unknown job ID #" + job );
	}
	catch( AlreadyPrinted ap)
	{
	    System.err.println("Could not cancel, job #" + job + " already printed");
	}
	catch( org.omg.CORBA.NO_PERMISSION np)
	{
	    System.err.println("Could not cancel, job #" + job + ", no permission");
	}

	for( int i = 0; i < 5; i++ )
	{
	    org.omg.CORBA.BooleanHolder bh = 
		new org.omg.CORBA.BooleanHolder();

	    try 
	    {
		// try to pull an event
		Any received =  proxyPullSupplier.try_pull(bh);	      
  		if( bh.value )
  		{
		    // got an event, check if we know how to deal with it
		    if( received.type().id().equals( 
			    "IDL:com/wiley/compbooks/brose/chapter11/office/PrinterStatus:1.0"))
		    {
			// extract the event data
			PrinterStatus printerStatus = PrinterStatusHelper.extract( received );
			// use this line for ORBs that correctly generate
			// "discriminator()" as the method for accessing
			// an IDL union's discriminator
			Status status = printerStatus.discriminator();

			// VisiBroker 4.0 needs this line:
                        //			Status status = printerStatus._discriminator();

			if( status == Status.PRINTED )
			    System.out.println("Job " + printerStatus.the_job().job_id + " was printed.");
			else if( status == Status.CANCELLED )
			    System.out.println("Job " + printerStatus.the_job().job_id + " was cancelled.");
		    }
		    else
			System.out.println("Unknown event.");
		}
		Thread.currentThread().sleep(2000);
	    } 
	    catch (Exception e) 
	    {
		e.printStackTrace();
	    }
	}

	// disconnect and shutdown
  	proxyPullSupplier.disconnect_pull_supplier();
	orb.shutdown(true);
    }
}


