// **********************************************************************
//
// Copyright (c) 1999
// Object Oriented Concepts, Inc.
// Billerica, MA, USA
//
// All Rights Reserved
//
// **********************************************************************

#include <OB/CORBA.h>
#include <OB/Util.h>

#include <Hello.h>
#include <Factory.h>

#include <stdlib.h>
#include <errno.h>

#ifdef HAVE_FSTREAM
#   include <fstream>
#else
#   include <fstream.h>
#endif

int
main(int argc, char* argv[], char*[])
{
    try
    {
	//
	// Create ORB
	//
	CORBA_ORB_var orb = CORBA_ORB_init(argc, argv);
	
	//
	// Get "hello" object
	//
	const char* refFile = "Factory.ref";
	ifstream in; // Must use open(name), not ifstream in(name) (VC++ bug)
	in.open(refFile);
	if(in.fail())
	{
	    cerr << argv[0] << ": can't open `" << refFile << "': "
		 << strerror(errno) << endl;
	    return 1;
	}
	
	char s[1000];
	in >> s;
	
	CORBA_Object_var obj = orb -> string_to_object(s);
	assert(!CORBA_is_nil(obj));
	
	Factory_var factory = Factory::_narrow(obj);
	assert(!CORBA_is_nil(factory));
	
	Hello_var hello;
	try
	{
	    hello = factory -> createHello();
	}
	catch(Factory::CreateFailed&)
	{
	    cerr << argv[0] << ": caught `CreateFailed' exception" << endl;
	    return 1;
	}

	//
	// Force connection to the hello client immediately.
	//
	if(hello -> _non_existent())
	{
	    cerr << argv[0] << ": `Hello' object does not exist" << endl;
	    return 1;
	}

	//
	// Main loop
	//
	cout << "Enter 'h' for hello or 'x' for exit:\n";
	char c;
	do
	{
	    cout << "> ";
	    cin >> c;
	    if(c == 'h')
		hello -> hello();
	}
	while(c != 'x');
    }
    catch(CORBA_SystemException& ex)
    {
	OBPrintException(ex);
	return 1;
    }

    return 0;
}

