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

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

#include <Event_impl.h>

//
// The ID of the next event.
//
CORBA_ULong Event_impl::nextId_ = 0;

//
// Mutex to protect the nextId_ member.
//
JTCMutex Event_impl::idMutex_;

// ----------------------------------------------------------------------
// Template instantiations
// ----------------------------------------------------------------------

#ifndef HAVE_NO_EXPLICIT_TEMPLATES
template class OBFixSeq<Event_impl*>;
#else
#ifdef HAVE_PRAGMA_DEFINE
#pragma define(OBFixSeq<Event_impl*>)
#endif
#endif

// ----------------------------------------------------------------------
// Event_impl constructor/destructor
// ----------------------------------------------------------------------

void
Event_impl::init(CORBA_ULong proxyId)
{
    {
        JTCSynchronized sync(idMutex_);
        id_ = nextId_++;
    }
    refCount_ = 1;

#ifdef OB_TRACE
    if(OBMessageViewer::instance() -> getTraceLevel() >= 3)
    {
        CORBA_String_var msg = CORBA_string_dup("Create Event(");
        msg += id_;
        msg += ") from ";
        msg += proxyId;
        OBMessageViewer::instance() -> trace(3, msg);
    }
#endif
}

// ----------------------------------------------------------------------
// Event_impl constructor/destructor
// ----------------------------------------------------------------------

Event_impl::Event_impl(const CORBA_Any& any, CORBA_ULong proxyId)
    : any_(any)
{
    init(proxyId);
}

Event_impl::Event_impl(CORBA_NVList_ptr args, const char* op,
                       CORBA_ULong proxyId)
    : args_(CORBA_NVList::_duplicate(args)),
      op_(CORBA_string_dup(op))
{
    init(proxyId);
}

Event_impl::~Event_impl()
{
#ifdef OB_TRACE
    if(OBMessageViewer::instance() -> getTraceLevel() >= 3)
    {
        CORBA_String_var msg = CORBA_string_dup("Destroy Event(");
        msg += id_;
        msg += ')';
        OBMessageViewer::instance() -> trace(3, msg);
    }
#endif
}

// ----------------------------------------------------------------------
// Event_impl public member functions
// ----------------------------------------------------------------------

void
Event_impl::discard()
{
    {
        JTCSynchronized sync(refMutex_);
        if(--refCount_ != 0)
            return;
    }
    delete this;
}

void
Event_impl::acquire()
{
    JTCSynchronized sync(refMutex_);
    ++refCount_;
}
