/*<<<***************************************************************************
The MIT License (MIT)

Copyright(C) 2013 - 2015 Marc Mirti Mancinelli, Christophe Lardau and Philippe Pamart (xdcube.org)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
#Title: xbPtr
#Project: xdcBase
////////////////////////////////////////////////////////////////////////////////
#Author: Marc MIRTI MANCINELLI
#History:
<15/09/2013: creation.
12/02/2014: this notice inserted.
***************************************************************************>>>*/
#include "stdafx.h"

#include "xbPtr.h"
#include "xbException.h"

#pragma warning(push)
#pragma warning(disable: 4311)
void xbObjectBase::Create()
{
	if (m_bCreated 
		&& (!m_bDestruction || !m_bReusable)) xbThrow xbEsys("xbObjectBase::Create() : already created");
	m_bCreated = true;
	if (m_bDestruction)
	{
		xbSectLock	lck(m_pSectPtr);
		m_bDestruction = false;
		m_bAddPtrAllowed = true;
	}
}

void xbObjectBase::Destroy()
{
	xbAssert(m_bCreated);
	m_bDestruction = true;

	onBeforeDestruction(true);
	{
		xbSectLock	lck(m_pSectPtr);
		m_bAddPtrAllowed = false;
		removeAllPtr(&lck);
	}
	onDestruction(true);
}

ULONG	xbObjectBase::addRef()
{
	xbAssert(m_bCreated);

	return ::xbInterlockIncrement32(&m_nRefCnt);
}

ULONG	xbObjectBase::release()
{
	long l = ::xbInterlockDecrement32(&m_nRefCnt);
	if (l == 0)
	{
		m_bDestruction = true;

		//release in two pass
		//In case of addref during removeAllPtr operation (...)
		// -> if xbObsPtr have a pointer on this object
		// & GetPtr is called on it.
		::xbInterlockIncrement32(&m_nRefCnt); 
		
		eProtect(onBeforeDestruction(false));
		eProtectBegin();
		{
			xbSectLock	lck(m_pSectPtr);
			m_bAddPtrAllowed = false;
			removeAllPtr(&lck);
		}
		eProtectEnd();
		eProtect(onDestruction(false));
		
		l = ::xbInterlockDecrement32(&m_nRefCnt);
		if (l == 0)
		{
			xbAssert(m_pFirstPtr == NULL);
			m_nRefCnt = 1;
			delete this;
		}
	}
	return l;
}

bool xbObjectBase::addPtr(sIxbPtr *pPtr,xbOpMode opm,bool bIfEmpty)
{
	int retryCnt = 0;
retry:
	{
		xbSectLock			lck(m_pSectPtr);
		xbLock				ptrLck(pPtr);
		if (!m_bCreated)
			xbThrow xbEsys("xbObjectBase::addPtr() : object not created");
		if (!m_bAddPtrAllowed)
		{
			if (opm == xbOp_Required) xbThrow xbEuser(E_ABORT,"Object in destruction or observers not allowed","xbObjectBase::addPtr()");
			return false;
		}
		
		if (pPtr->_isPtrValid())
		{
			if (bIfEmpty)
				return false;

			if (pPtr->HasObject(this)) 
				return true;

			ptrLck.Unlock();
			lck.Unlock();
			
			if (retryCnt>5) 
				xbThrow xbEsys("xbObjectBase::addPtr() : Can't affect observer, too many tries");

			pPtr->Unlink(NULL,true);
			retryCnt++;
			goto retry;
		}
		
		pPtr->_link(this,&m_pFirstPtr);
	}

	xbRdbgAssert(!m_pSectPtr || !m_pSectPtr->IsLockedByMe());
	xbPtrNotif ptrNotif(this,false);
	pPtr->onLink(&ptrNotif);
	ptrNotif.onLink();
	return true;
}

void xbObjectBase::removePtr(sIxbPtr *pPtr,bool bAddAfter,sIxbPtrNotif *pPtrNotif)
{
	{
		xbSectLock	lck(m_pSectPtr);
		xbLock		ptrLck(pPtr);
		if (!pPtr->HasObject(this)) 
			return;
//			xbThrow xbEsys("xbObjectBase::removePtr() : ptr not attached to this object");
		pPtr->_unlink(&m_pFirstPtr,&lck);
	}
	if (bAddAfter) 
		return;
	if (pPtrNotif)
		pPtr->onUnlink(pPtrNotif);
	else
	{
		xbRdbgAssert(!m_pSectPtr || !m_pSectPtr->IsLockedByMe());
		xbPtrNotif ptrNotif(this,false);
		pPtr->onUnlink(&ptrNotif);
		ptrNotif.onUnlink();
	}
}

void xbObjectBase::removeAllPtr(xbSectLock *pLck)
{
	xbPtrNotif ptrNotif(this,true);
	if (!pLck->IsLocked())
		pLck->Lock(m_pSectPtr);
	sIxbPtr *ptr = m_pFirstPtr;
	while(ptr) 
	{
		sIxbPtr *pNext = ptr->_getNext();
		if (ptr->_isPtrProtected()) 
			ptr->Unlink(&ptrNotif,false);
		ptr = pNext;
	}
	if (ptrNotif.hasObjectToNotif())
	{
		pLck->Unlock();
		xbRdbgAssert(!m_pSectPtr || !m_pSectPtr->IsLockedByMe());
		ptrNotif.onUnlink();
	}
}

void xbObjectBase::signalPtr(int arg)
{
	xbPtrNotif ptrNotif(this,true);
	xbSectLock	lck(m_pSectPtr);
	sIxbPtr		*pPtr = m_pFirstPtr;
	while(pPtr) 
	{
		sIxbPtr *pNext = pPtr->_getNext();
		pPtr->onSignal(&ptrNotif,arg);
		pPtr = pNext;
	}
	if (ptrNotif.hasObjectToNotif())
	{
		lck.Unlock();
		xbRdbgAssert(!m_pSectPtr || !m_pSectPtr->IsLockedByMe());
		ptrNotif.onSignal(arg);
	}
}

void xbPtrNotif::onSignal(int arg)
{
	if (m_arrObj.IsEmpty())
		return;

	m_bObjAdded = false;
	m_bSectLocked = false;
	xbRefPtr<IxbObjectPtrNotif> *pprObj = m_arrObj.Begin();
	xbRefPtr<IxbObjectPtrNotif> *pprEnd = m_arrObj.End();
	while(pprObj < pprEnd)
	{
		(*pprObj)->onPtrSignal(this,arg);
		if (!m_bObjAdded)
		{
			pprObj++;
			continue;
		}
		m_bObjAdded = false;
		int ix = int((xbNptr(pprObj) - xbNptr(m_arrObj.Begin()))/sizeof(*pprObj));
		pprObj = m_arrObj.Begin()+ix+1;
		pprEnd = m_arrObj.End();
	}
}

void xbPtrNotif::onLink()
{
	if (m_arrObj.IsEmpty())
		return;

	m_bObjAdded = false;
	m_bSectLocked = false;
	xbRefPtr<IxbObjectPtrNotif> *pprObj = m_arrObj.Begin();
	xbRefPtr<IxbObjectPtrNotif> *pprEnd = m_arrObj.End();
	while(pprObj < pprEnd)
	{
		(*pprObj)->onPtrLink(this);
		if (!m_bObjAdded)
		{
			pprObj++;
			continue;
		}
		m_bObjAdded = false;
		int ix = int((xbNptr(pprObj) - xbNptr(m_arrObj.Begin()))/sizeof(*pprObj));
		pprObj = m_arrObj.Begin()+ix+1;
		pprEnd = m_arrObj.End();
	}
}

void xbPtrNotif::onUnlink()
{
	if (m_arrObj.IsEmpty())
		return;

	m_bObjAdded = false;
	m_bSectLocked = false;
	xbRefPtr<IxbObjectPtrNotif> *pprObj = m_arrObj.Begin();
	xbRefPtr<IxbObjectPtrNotif> *pprEnd = m_arrObj.End();
	while(pprObj < pprEnd)
	{
		(*pprObj)->onPtrUnlink(this);
		if (!m_bObjAdded)
		{
			pprObj++;
			continue;
		}
		m_bObjAdded = false;
		int ix = int((xbNptr(pprObj) - xbNptr(m_arrObj.Begin()))/sizeof(*pprObj));
		pprObj = m_arrObj.Begin()+ix+1;
		pprEnd = m_arrObj.End();
	}
}

bool xbPtrNotif::HasObjectToNotif(IxbObjectPtrNotif *pObj)
{
	xbRefPtr<IxbObjectPtrNotif> *pprObj = m_arrObj.Begin();
	xbRefPtr<IxbObjectPtrNotif> *pprEnd = m_arrObj.End();
	while(pprObj < pprEnd)
	{
		if (pprObj->IsEqualObject(pObj))
			return true;
		pprObj++;
	}
	return false;
}
#pragma warning(pop)
