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

#include <assert.h>
#include <stdlib.h>
#include <string.h>

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

#include <OB/CosNaming.h>

#include "TestObject_impl.h"
#include "TestMacro.h"


//
// Test CosNaming::NamingContext::destroy()
//
void
TestDestroy(CORBA_ORB_ptr orb, CosNaming_NamingContext_ptr root)
{
    TestObject_var test = new TestObject_impl;
    CosNaming_Name name1, name2;
    CosNaming_NamingContext_var context;

    //
    // Test exceptions
    //

    context = root -> new_context();
    name1.length(1);
    name1[0].id = CORBA_string_dup("ctx");
    name1[0].kind = CORBA_string_dup("");
    SUCCEED(root -> bind_context(name1, context));

    name2.length(1);
    name2[0].id = CORBA_string_dup("object");
    name2[0].kind = CORBA_string_dup("");
    SUCCEED(context -> bind(name2, test));

    try
    {
        //
        // Try to destroy a context that's not empty
        //
        context -> destroy();
        assert("destroy should not have succeeded" == 0);
    }
    catch(CosNaming_NamingContext::NotEmpty&)
    {
        // expected
    }

    SUCCEED(context -> unbind(name2));

    //
    // Destroy the context while there is still a binding in the root
    // context.
    //
    SUCCEED(context -> destroy());

    //
    // Ensure that the context has been destroyed.
    //
    try
    {
	context -> unbind(name1);
	assert("Call on context should not have succeeded." == 0);
    }
    catch(CORBA_OBJECT_NOT_EXIST&)
    {
	// Expected
    }

    //
    // Resolve the context, and attempt a method call.
    //
    CORBA_Object_var obj;
    SUCCEED(obj = root -> resolve(name1));

    //
    // Ensure that the context has been destroyed.
    //
    try
    {
        CosNaming_NamingContext_var contextAgain =
            CosNaming_NamingContext::_narrow(obj);
        assert(!CORBA_is_nil(contextAgain));

	contextAgain -> unbind(name1);
	assert("Call on context should not have succeeded." == 0);
    }
    catch(CORBA_OBJECT_NOT_EXIST&)
    {
	// Expected
    }

    //
    // This test should succeed, but doesn't. This is because the
    // context is reconnected implicitely in the naming service.
    // Eventually this test should succeed.
    //
    //assert(context -> _is_equivalent(contextAgain));

    //
    // Now unbind.
    //
    SUCCEED(root -> unbind(name1));
}
