//______________________________________________________________________________
//
// Класс-указатель на CBLContext, определенный через CValue
//______________________________________________________________________________
//

#include "stdafx.h"
#include "SafeContext.h"

BOOL CSafeContext::debug() const
{
	return FALSE;
};

void CSafeContext::Assign(const CBLContext *pCont) //const
{
	Release();
	
	if (pCont)
	{
		if (debug())
			Msg("Create m_pValue * %p %p %s:%s", this, pCont, pCont->GetRuntimeClass()->m_lpszClassName, pCont->GetTypeString());
		
		m_pValue = new CValue;
		m_pValue->AssignContext(const_cast<CBLContext *>(pCont));
		
		m_bIsGroupContext = pCont->IsKindOf( RUNTIME_CLASS( CGroupContext ));
	}
};

void CSafeContext::Release() //const
{
	if (m_pValue)
	{
		if (debug())
		{
			CBLContext *pCont = m_pValue->GetContext();
			if(pCont)
				Msg("Delete m_pValue * %p %p %s:%s", this, pCont, pCont->GetRuntimeClass()->m_lpszClassName, pCont->GetTypeString());
			else
				Msg("Delete NULL_CONTEXT  m_pValue, %p %p", this, pCont);
		}
		
		delete m_pValue;
		
		m_pValue = NULL;
		m_bIsGroupContext = FALSE;
	}
};

CSafeContext::CSafeContext(BOOL bFlagAutoDestroy) : m_pValue(NULL), m_bIsGroupContext(FALSE), m_bFlagAutoDestroy(bFlagAutoDestroy)
{
};

CSafeContext::CSafeContext(CBLContext *pCont, BOOL bFlagAutoDestroy) : m_pValue(NULL), m_bIsGroupContext(FALSE), m_bFlagAutoDestroy(bFlagAutoDestroy)
{ 
	Assign(pCont);
};

CSafeContext::CSafeContext(const CSafeContext& ref) : m_pValue(NULL), m_bIsGroupContext(FALSE), m_bFlagAutoDestroy(ref.m_bFlagAutoDestroy)
{
	if (ref.m_pValue)
		Assign(ref.m_pValue->GetContext());

	if (!m_bFlagAutoDestroy)
		IncrRef();
};

CSafeContext::CSafeContext(LPCSTR szName, BOOL bFlagAutoDestroy) : m_pValue(NULL), m_bIsGroupContext(FALSE), m_bFlagAutoDestroy(bFlagAutoDestroy)
{
	CBLContext* pCont = NULL;
	try
	{
		pCont = CBLContext::CreateInstance(szName);
	}
	catch(...)
	{
	};
	
	Assign(pCont);
};

CSafeContext::~CSafeContext()
{
	if (debug())
		Msg("Destructor CSafeContext");

	if (m_bFlagAutoDestroy)
		DecrRef();

	Release();
};

BOOL CSafeContext::IsGroupContext() const
{
	return m_bIsGroupContext;
};

void CSafeContext::IncrRef()
{
	if (m_pValue && !m_bIsGroupContext)
	{
		CBLContext *pCont = m_pValue->GetContext();
		if (pCont)
			pCont->IncrRef();
		
	}
};

void CSafeContext::DecrRef()
{
	if (m_pValue && !m_bIsGroupContext)
	{
		CBLContext *pCont = m_pValue->GetContext();
		if (pCont)
			pCont->DecrRef();
		
	}
};

CSafeContext& CSafeContext::operator =(const CBLContext* pCont) //const
{
	if (m_bFlagAutoDestroy)
		DecrRef();

	Assign(pCont);
	return *this;
};

CSafeContext::operator bool() const
{
	return (m_pValue && m_pValue->GetContext());
};

CSafeContext::operator !() const
{ 
	return !operator bool();
};

CSafeContext::operator CBLContext *() const
{
	CBLContext *pCont = NULL;
	
	if (m_pValue)
		pCont = m_pValue->GetContext();
	
	return pCont;
};


