/*<<<***************************************************************************
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: xbSharedQueue
#Project: xdcBase
////////////////////////////////////////////////////////////////////////////////
#Author: Marc MIRTI MANCINELLI
#History:
<15/09/2013: creation.
12/02/2014: this notice inserted.
***************************************************************************>>>*/
#include "stdafx.h"

#include "xbSharedQueue.h"
#include "xbFileTools.h"

#pragma warning(push)
#pragma warning(disable: 4311) //troncation de pointeur de 'LPCSTR' à 'int'

const GUID &xbSharedQueue::GetFileID() const
{
	return __uuidof(_xbSharedQ);
}

void xbSharedQueue::init()
{
	m_bClosed = true;
//	m_pQ = NULL;
	m_processId = ::GetCurrentProcessId();
	m_qEvent.Create(&m_attr,m_name.IsEmpty()?xbString():m_name+".EprocessQ"+xbString(uint(m_processId)));
}

void xbSharedQueue::Create()
{
	xbSharedHeap::Create();
	try
	{
		xbDateTime	dt = xbDateTime::UtcNow();
		xbRefPtr<xbSharedMem>	prQ;
		xbLock lck(&m_mutex);
		if (m_prQ.IsValid()) 
		{
			m_bClosed = false;
			return;
		}
		if (m_qName.IsEmpty())
		{
			m_qName = ::xbGetFileName((HMODULE)NULL);
			if (m_qName.IsEmpty() || m_qName.First() == char(255))
				xbThrowEsys("xbSharedQueue('"+xbString(m_filepath)+"')::Create() : bad qName('"+m_qName+"')");
		}

		_xbSharedQ	*pQ;
		int cByte = sizeof(_xbSharedQ)-sizeof(pQ->m_name)+m_qName.Length+1;
		if (cByte < sizeof(_xbSharedQ))
			cByte = sizeof(_xbSharedQ);
		Alloc(&prQ,cByte);

		xbMemLock	memLck(prQ);
		pQ = (_xbSharedQ*)memLck.GetPtr();
		memset(pQ,0,cByte);
		pQ->m_processId = m_processId;
		pQ->m_lastAccess = dt;
		pQ->m_hQueueNext = m_pHdr->m_mainBlockId;
		strcpy(pQ->m_name,m_qName);

		xbRefPtr<xbSharedMem>	prQnext;
		if (m_pHdr->m_mainBlockId.IsValid())
		{
			if (!Load(&prQnext,m_pHdr->m_mainBlockId,0,xbOp_Optional))
			{
				xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::Create() : mainblock pointer invalid");
				m_pHdr->m_mainBlockId = xbSharedHandle();
			}
		}

		if (prQnext.IsValid())
		{
			xbMemLock	memLckNext(prQnext);
			_xbSharedQ	*pQnext = (_xbSharedQ*)memLckNext.GetPtr();
	
			pQnext->m_hQueuePrev = prQ->GetHandle();
		
			pQ->m_hQueueNext = m_pHdr->m_mainBlockId;
		}

		m_pHdr->m_mainBlockId = prQ->GetHandle();

		m_prQ = prQ;

		m_bClosed = false;

		xbDbgOutput("xbSharedQueue("+m_filepath+")::Create() : qname="+xbString(m_qName));
	}
	catch(...)
	{
		eProtect(Destroy());
		throw;
	}
}

void xbSharedQueue::Destroy()
{
	eProtectBegin();

	xbRefPtr<xbSharedMem>	prQ;
	{
		xbLock lck(&m_mutex);
		prQ = m_prQ;
		m_prQ.Empty();
		m_bClosed = true;
		if (prQ.IsValid())
		{
			m_bNoMemLocks = false;
			xbMemLock	memLck(prQ);
			_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();
			if (!pQ->m_processId || pQ->m_processId == m_processId)
				deleteQ(pQ,false,true);
		}
	}
	
	eProtectEndTrace();
	m_bClosed = true;
	m_bNoMemLocks = true;
	xbSharedHeap::Destroy();
}

bool xbSharedQueue::Alloc(xbRefPtr<xbSharedMem> *pprMem,ulong cByte,xbOpMode opm)
{
	bool bFirst = true;
	int cCnt = 0;
	for(;;)
	{
		if (xbSharedHeap::Alloc(pprMem,cByte,xbOp_Optional))
			return true;
		if (opm == xbOp_Optional)
			return false;
		if (bFirst)
		{
			bFirst = false;
			if (CleanQlist())
				continue;
		}
		if (++cCnt > 10)
			xbThrowEsys(E_OUTOFMEMORY,"xbSharedQueue('"+xbString(m_filepath)+"')::Alloc() : heap full");
		::xbSleep(300);
	}
}

void xbSharedQueue::SetQueueName(LPCSTR pQueueName)
{
	xbLock lck(&m_mutex);
	if (m_prQ.IsValid())
		xbThrowEsys("xbSharedQueue('"+xbString(m_filepath)+"')::SetQueueName("+xbString(pQueueName)+") : queue already created, can't change name");
	m_qName = pQueueName;
}

bool xbSharedQueue::CleanQlist()
{
	bool bRet = false;
	xbDateTime dt(xbDateTime::UtcNow());
#ifdef _DEBUG
	dt -= double(1.0) /(24.0 * 60.0) * 4;
#else
	dt -= double(1.0) /(24.0 * 60.0) * 20;
#endif

	xbLock lck(&m_mutex);
	if (!m_pHdr) 
		xbThrowEsys("xbSharedQueue('"+m_filepath+"')::CleanQlist() : queue not created");
	xbSharedHandle hQ = m_pHdr->m_mainBlockId;
	xbRefPtr<xbSharedMem>	prQ;
	int index = 0;
	while(hQ.IsValid())
	{
		if (!Load(&prQ,hQ,0,xbOp_Optional))
		{
			if (m_pHdr->m_mainBlockId.m_handle == hQ.m_handle)
				xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::CleanQlist() : mainblock pointer invalid");
			else
				xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::CleanQlist() : next pointer invalid");
			break;
		}
		if (++index > xbQTARGET_APPMAX)
		{
			xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::CleanQlist() : maybe a pb in chained list : more than "+xbString(xbQTARGET_APPMAX)+" q processes !! nb="+xbString(index));
			break;
		}
		{
			xbMemLock	memLck(prQ);
			_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();
			hQ = pQ->m_hQueueNext;
			if (pQ->m_lastAccess >= (double)dt
				&& pQ->m_processId != 0)
				continue;
			if (pQ->m_processId != 0 && m_name.IsValid())
			{
				eProtectBegin();
				xbEvent qEv(xbCtor_NoOp);
				if (!qEv.Create(&m_attr,m_name+".EprocessQ"+xbString(uint(pQ->m_processId))))
				{
					eProtectTrace(xbRelOutput("INFO: xbSharedQueue('"+xbString(m_filepath)+"')::CleanQlist() :"
						" q deleted but not freed : name="+xbString(pQ->m_name)+", processId="+xbString(pQ->m_processId)+", lastAccess="+xbDateTime(pQ->m_lastAccess).ToString()));

					eProtectTrace(deleteQ(pQ,true,true));
					continue;
				}
				eProtectEnd();
			}

			eProtectTrace(xbRelOutput("INFO: xbSharedQueue('"+xbString(m_filepath)+"')::CleanQlist() :"
				" q deleted : name="+xbString(pQ->m_name)+", processId="+xbString(pQ->m_processId)+", lastAccess="+xbDateTime(pQ->m_lastAccess).ToString()));
			eProtectTrace(deleteQ(pQ,true,true));
		}

		prQ->UnlockUse();
		bRet = true;
	}
	return bRet;
}

void xbSharedQueue::deleteQ(_xbSharedQ *pQ,bool bInChain,bool bDelChain)
{
	if (bDelChain)
	{
		if (pQ->m_name[0] == char(255))
		{
			if (bInChain)
				xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::Destroy() : q already destroyed in chain !!");
		}
		else
		{
			pQ->m_name[0] = char(255);

			xbRefPtr<xbSharedMem>	prQnext;
			if (pQ->m_hQueueNext.IsValid())
			{
				if (!Load(&prQnext,pQ->m_hQueueNext,0,xbOp_Optional))
				{
					xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::Destroy() : previous pointer invalid");
					pQ->m_hQueueNext = xbSharedHandle();
				}
			}
			xbRefPtr<xbSharedMem>	prQprev;
			if (pQ->m_hQueuePrev.IsValid())
			{
				if (!Load(&prQprev,pQ->m_hQueuePrev,0,xbOp_Optional))
				{
					xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::Destroy() : next pointer invalid");
					pQ->m_hQueuePrev = xbSharedHandle();
				}
			}

			if (prQprev.IsEmpty())
				m_pHdr->m_mainBlockId = pQ->m_hQueueNext;
			else
			{
				xbMemLock	memLckPrev(prQprev);
				_xbSharedQ	*pQprev = (_xbSharedQ*)memLckPrev.GetPtr();

				pQprev->m_hQueueNext = pQ->m_hQueueNext;
			}

			if (prQnext.IsValid())
			{
				xbMemLock	memLckNext(prQnext);
				_xbSharedQ	*pQnext = (_xbSharedQ*)memLckNext.GetPtr();

				pQnext->m_hQueuePrev = pQ->m_hQueuePrev;
			}
		}

		pQ->m_processId = 0;
		pQ->m_hQueueNext = xbSharedHandle();
		pQ->m_hQueuePrev = xbSharedHandle();
	}
	else
	{
		pQ->m_lastAccess = xbDateTime::UtcNow();
	}

	_xbSharedMsg *pMsg = pQ->m_msg;
	_xbSharedMsg *pMsgEnd = pQ->m_msg + pQ->m_cMsgWaiting;

	while(pMsg < pMsgEnd)
	{
		eProtectTrace(deleteMsg(pMsg));
		pMsg++;
	}
	pQ->m_cMsgWaiting = 0;
}

void xbSharedQueue::deleteMsg(_xbSharedMsg *pMsg)
{
	if (pMsg->m_hData.IsEmpty())
		return;
	xbSharedHandle hData = pMsg->m_hData;
	pMsg->m_hData = xbSharedHandle();
	xbRefPtr<xbSharedMem>	prData;
	if (!Load(&prData,hData,0,xbOp_Optional))
	{
		xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::deleteMsg() : data pointer invalid");
		return;
	}
	prData->UnlockUse();
}

void xbSharedQueue::Close()
{
	{
		xbLock lck(&m_mutex);
		m_bClosed = true;
	}
	m_qEvent.Set();
}

void xbSharedQueue::CancelClose()
{
	xbLock lck(&m_mutex);
	m_bClosed = false;
	m_bNoMemLocks = false;
}

bool xbSharedQueue::IsClosed() const
{
	xbLock lck(&m_mutex);
	return m_bClosed;
}

bool xbSharedQueue::Peek(ulong *pMsgId,xbRefPtr<xbSharedMem> *pprMem,ulong *pWparam,ulong *pLparam,bool bRemove)
{
	xbDateTime dt(xbDateTime::UtcNow());
	xbLock lck(&m_mutex);
	if (m_prQ.IsEmpty())
		return false;
	xbMemLock	memLck(m_prQ);
	_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();
	if (pQ->m_processId != m_processId)
		xbThrowEsys("xbSharedQueue('"+xbString(m_filepath)+"')::Peek() : queue attached to another process");

	pQ->m_lastAccess = dt;
	if (pQ->m_cMsgWaiting <= 0)
		return false;

	_xbSharedMsg msg = pQ->m_msg[0];
	if (bRemove)
	{
		pQ->m_cMsgWaiting--;
		if (pQ->m_cMsgWaiting>0)
			::memmove(&pQ->m_msg[0],&pQ->m_msg[1],pQ->m_cMsgWaiting * sizeof(msg));
		lck.Unlock();
	}
	if (pMsgId) *pMsgId = msg.m_msgId;
	if (pWparam) *pWparam = msg.m_wParam;
	if (pLparam) *pLparam = msg.m_lParam;
	if (msg.m_hData.IsValid())
	{
		xbRefPtr<xbSharedMem>	prData;
		if (!Load(&prData,msg.m_hData,0,xbOp_Optional))
		{
			xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::deleteMsg() : data pointer invalid");
			if (pprMem)
				pprMem->Empty();
			return true;
		}
		if (bRemove)
			prData->UnlockUse();
		if (pprMem)
			*pprMem = prData;
	}
	else
	{
		if (pprMem)
			pprMem->Empty();
	}
	return true;
}

bool xbSharedQueue::Wait(bool *pbTimeOut,bool *pbCancel)
{
	{
		xbLock lck(&m_mutex);
		if (m_prQ.IsEmpty() || m_bClosed)
		{
			if (pbTimeOut)
				*pbTimeOut = false;
			if (pbCancel)
				*pbCancel = false;
			return false;
		}
	}
	bool bCancel = false;
	if (pbTimeOut && !pbCancel)
		pbCancel = &bCancel;
	if (!m_qEvent.Wait(pbCancel))
	{
		if (pbTimeOut)
			*pbTimeOut = !(*pbCancel);
		return false;
	}
	if (pbTimeOut)
		*pbTimeOut = false;
	return true;
}

bool xbSharedQueue::Wait(xbEvent &ev2,bool *pbTimeOut,bool *pbCancel)
{
	{
		xbLock lck(&m_mutex);
		if (m_prQ.IsEmpty() || m_bClosed)
		{
			if (pbTimeOut)
				*pbTimeOut = false;
			if (pbCancel)
				*pbCancel = false;
			return false;
		}
	}
	bool bCancel = false;
	if (pbTimeOut && !pbCancel)
		pbCancel = &bCancel;
	if (!m_qEvent.wait(ev2,xbWAIT_TIMEOUTDFLT,pbCancel))
	{
		if (pbTimeOut)
			*pbTimeOut = !(*pbCancel);
		return false;
	}
	if (pbTimeOut)
		*pbTimeOut = false;
	return true;
}

bool xbSharedQueueEnum::onGetNext()
{
	for(;;)
	{
		xbSharedHandle	hQ;
		if (m_prQ.IsEmpty())
		{
			if (!m_pParent) 
				xbThrowEsys("xbSharedQueueEnum()::onGetNext() : no queue attached");
			m_lckqMutex.Lock(m_pParent);
			if (!m_pParent->m_pHdr) 
			{
				m_lckqMutex.Unlock();
				xbThrowEsys("xbSharedQueueEnum('"+m_pParent->m_filepath+"')::onGetNext() : queue not created");
			}
			hQ = m_pParent->m_pHdr->m_mainBlockId;
			m_index=0;
		}
		else
		{
			xbMemLock	memLck(m_prQ);
			_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();
			hQ = pQ->m_hQueueNext;
		}
		if (hQ.IsEmpty())
			return false;

		xbRefPtr<xbSharedMem>	prQ;
		if (!m_pParent->Load(&prQ,hQ,0,xbOp_Optional) || prQ.IsEmpty())
		{
			if (m_pParent->m_pHdr->m_mainBlockId.m_handle == hQ.m_handle)
				xbRelOutput("ERROR: xbSharedQueueEnum('"+xbString(m_pParent->m_filepath)+"')::onGetNext() : mainblock pointer invalid");
			else
				xbRelOutput("ERROR: xbSharedQueueEnum('"+xbString(m_pParent->m_filepath)+"')::onGetNext() : next pointer invalid");
			return false;
		}
		if (++m_index > xbQTARGET_APPMAX)
		{
			xbRelOutput("ERROR: xbSharedQueueEnum('"+xbString(m_pParent->m_filepath)+"')::onGetNext() : maybe a pb in chained list : more than "+xbString(xbQTARGET_APPMAX)+" q processes !! nb="+xbString(m_index));
			return false;
		}
		m_prQ = prQ;
		if (m_excludeProcessId)
		{
			xbMemLock	memLck(m_prQ);
			_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();
			if (pQ->m_processId == m_excludeProcessId)
				continue;
		}

		break;
	}

	return true;
}

bool xbSharedQueueEnum::onKeysOk(const Cond *pCond,ulong mode) const
{
	xbMemLock	memLck(m_prQ);
	_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();

	xbDbgOutput("bSharedQueueSearch::onKeysOk() : qName="+xbString(pQ->m_name)
		+", processId="+xbString(pQ->m_processId,xbStringNum_hexa));

	if (mode & Search_Name)
	{
		if (pCond->IsKeyOk(pQ->m_name,mode)) return true;
	}

	if (mode & Search_ProcessId)
	{
		if (pCond->IsKeyOk(xbString(pQ->m_processId),mode)) return true;
	}
	return false;
}

bool xbSharedQueueEnum::onFlagSet(bool bFirst,const xbString &str,int op,ulong *pmode) const
{
	if (str.CompareNoCase("name") == 0)
	{
		if (op == 1) (*pmode) |= Search_Name;
		else if (op == -1) (*pmode) &= ~Search_Name;
		else 
		{
			if (bFirst) (*pmode) &= ~Search_All;
			(*pmode) |= Search_Name;
		}
		return true;
	}
	if (str.CompareNoCase("processid") == 0)
	{
		if (op == 1) (*pmode) |= Search_ProcessId;
		else if (op == -1) (*pmode) &= ~Search_ProcessId;
		else 
		{
			if (bFirst) (*pmode) &= ~Search_All;
			(*pmode) |= Search_ProcessId;
		}
		return true;
	}
	return false;
}

xbString	xbSharedQueueEnum::GetQname() const
{
	if (m_prQ.IsEmpty())
		xbThrowEsys("xbSharedQueueEnum()::GetQname() : no current queue selected");
	xbMemLock	memLck(m_prQ);
	_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();

	return pQ->m_name;
}

DWORD		xbSharedQueueEnum::GetQprocess() const
{
	if (m_prQ.IsEmpty())
		xbThrowEsys("xbSharedQueueEnum()::GetQprocess() : no current queue selected");
	xbMemLock	memLck(m_prQ);
	_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();

	return pQ->m_processId;
}

xbDateTime		xbSharedQueueEnum::GetQlastAccess() const
{
	if (m_prQ.IsEmpty())
		xbThrowEsys("xbSharedQueueEnum()::GetQlastAccess() : no current queue selected");
	xbMemLock	memLck(m_prQ);
	_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();

	return pQ->m_lastAccess;
}

int xbSharedQueue::Post(LPCSTR target,ulong msgId,const void *pData,int cByte,ulong wParam, ulong lParam)
{
	xbRefPtr<xbSharedMem>	prData;
	if (pData && cByte > 0)
	{
		Alloc(&prData,cByte);
		xbMemLock lck(prData);
		memcpy(lck.GetPtr(),pData,cByte);
	}
	return Post(target,msgId,prData,wParam,lParam);
}

int xbSharedQueue::Post(LPCSTR target,ulong msgId,xbSharedMem *pMem,ulong wParam, ulong lParam)
{
	int ret = 0;

	xbArray<ulong>	arrProcessToRetry;
	{
		xbSharedQueueEnum	qenum;
		switch(int(target))
		{
		case int(xbQTARGET_ALL):
			qenum.SearchSubString(xbString(),xbSharedQueueEnum::Search_Name);
			qenum.Start(this);
			break;
		case int(xbQTARGET_ALLANDTHIS):
			qenum.SearchSubString(xbString(),xbSharedQueueEnum::Search_Name);
			qenum.Start(this,false);
			break;
		case int(xbQTARGET_THIS):
			{
				xbLock lck(&m_mutex);
				ulong processIdToRetry;
				if (post(m_prQ,msgId,pMem,wParam,lParam,&processIdToRetry))
					return 1;

				if (!processIdToRetry)
					return 0;

				arrProcessToRetry.Add(processIdToRetry);
				break;
			}
			return 1;
		default:
			if (*target == '§')
			{
				qenum.SearchExpr(target+1,xbSharedQueueEnum::Search_Name);
				qenum.Start(this,false);
			}
			else
			{
				qenum.SearchExpr(target,xbSharedQueueEnum::Search_Name);
				qenum.Start(this,true);
			}
			break;
		};

		if (arrProcessToRetry.IsEmpty())
		{
			while(qenum.SearchNext())
			{
//				ulong processIdToRetry = qenum.GetQprocess();
				ulong processIdToRetry = 0;
				if (post(qenum.getQptr(),msgId,pMem,wParam,lParam,&processIdToRetry))
				{
					ret++;
					continue;
				}

				if (!processIdToRetry)
					continue;

				arrProcessToRetry.Add(processIdToRetry);
			}
		}
	}
	
	int cnt = 0;
	while(arrProcessToRetry.IsValid())
	{
		if (++cnt > 20)
			xbThrowEsys(xbHR_TIMEOUT,"xbSharedQueue('"+xbString(m_filepath)+"')::Post() : timeout");

		::xbSleep(300);
		
		xbArray<ulong>	arrProcess;
		arrProcess.Attach(&arrProcessToRetry);

		ret += post(arrProcess,msgId,pMem,wParam,lParam,&arrProcessToRetry);
	}

	return ret;
}

bool xbSharedQueue::post(xbSharedMem *pTarget,ulong msgId,xbSharedMem *pMem,ulong wParam, ulong lParam,ulong *pProcessToRetry)
{
	xbLock lck(&m_mutex);

	xbMemLock	memLck(pTarget);
	_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();
	if (!pQ->m_processId)
	{
		if (pProcessToRetry)
			*pProcessToRetry = 0;
		return false;
	}

	if (pQ->m_cMsgWaiting >= _xbSharedQ_SIZE)
	{
		if (m_name.IsEmpty() || pQ->m_processId == m_processId)
			m_qEvent.Set();
		else
		{
			xbEvent qEv(xbCtor_NoOp);
			if (qEv.Create(&m_attr,m_name+".EprocessQ"+xbString(uint(pQ->m_processId))))
			{
				xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::post() : event doesn't exist for processid="+xbString(pQ->m_processId)+" (on queue full)");
				pQ->m_processId = 0;
			}
			else 
				qEv.Set();
		}
		if (pProcessToRetry)
			*pProcessToRetry = pQ->m_processId;
		return false;
	}
	_xbSharedMsg *pMsg = pQ->m_msg + pQ->m_cMsgWaiting;
	pMsg->m_msgId = msgId;
	pMsg->m_wParam = wParam;
	pMsg->m_lParam = lParam;
	if (!pMem)
		pMsg->m_hData = xbSharedHandle();
	else
	{
		pMsg->m_hData = pMem->GetHandle();
		pMem->LockUse();
	}
	pQ->m_cMsgWaiting++;
	ulong processId = pQ->m_processId;

	if (m_name.IsEmpty() || processId == m_processId)
		m_qEvent.Set();
	else
	{
		xbEvent qEv(xbCtor_NoOp);
		if (qEv.Create(&m_attr,m_name+".EprocessQ"+xbString(uint(processId))))
		{
			xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::post() : event doesn't exist for processid="+xbString(processId));
			pQ->m_processId = 0;
			return false;
		}
		qEv.Set();
	}
	return true;
}

int xbSharedQueue::post(xbArray<ulong> &processes,ulong msgId,xbSharedMem *pMem,ulong wParam, ulong lParam,xbArray<ulong> *pProcessesToRetry)
{
	int ret = 0;
	xbLock lck(&m_mutex);
	if (!m_pHdr) 
		xbThrowEsys("xbSharedQueue('"+m_filepath+"')::post() : queue not created");
	xbSharedHandle hQ = m_pHdr->m_mainBlockId;
	int index = 0;
	xbRefPtr<xbSharedMem>	prQ;
	while(hQ.IsValid())
	{
		if (++index > xbQTARGET_APPMAX)
		{
			xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::post() : maybe a pb in chained list : more than "+xbString(xbQTARGET_APPMAX)+" q processes !! nb="+xbString(index));
			break;
		}
		if (!Load(&prQ,hQ,0,xbOp_Optional))
		{
			if (m_pHdr->m_mainBlockId.m_handle == hQ.m_handle)
				xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::post() : mainblock pointer invalid");
			else
				xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::post() : next pointer invalid");
			break;
		}
		xbMemLock	memLck(prQ);
		_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();
		hQ = pQ->m_hQueueNext;

		ulong processId = pQ->m_processId;
		if (!processId)
			continue;

		ulong *ptr = processes.Begin();
		int no = 0, lg = processes.Length;
		while(no < lg)
		{
			if (*ptr == processId)
			{
				processes.Delete(no);
				no = -1;
				break;
			}
			ptr++;
			no++;
		}
		if (no >= 0) 
			continue;
		ulong processIdToRetry = 0;

		if (post(prQ,msgId,pMem,wParam,lParam,&processIdToRetry))
		{
			ret++;
			continue;
		}

		if (!processIdToRetry)
			continue;

		pProcessesToRetry->Add(processIdToRetry);
	}
	return ret;
}

int xbSharedQueue::Check()
{
	int nberr = xbSharedHeap::Check();

	xbLock lck(&m_mutex);
	if (!m_pHdr) 
		xbThrowEsys("xbSharedQueue('"+m_filepath+"')::Check() : queue not created");
	bool bContinue = true;
	bool bDisp = false;
//	bool bDisp = true;
	while(bContinue)
	{
		bContinue = false;
		xbSharedHandle hQ = m_pHdr->m_mainBlockId,hQprev;
		int index = 0;
		xbRefPtr<xbSharedMem>	prQ;
		while(hQ.IsValid())
		{
			if (++index > xbQTARGET_APPMAX)
			{
				xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::Check() : maybe a pb in chained list : more than "+xbString(xbQTARGET_APPMAX)+" q processes !! nb="+xbString(index));
				bContinue = !bDisp;
				if (bDisp)
					nberr++;
				break;
			}
			if (!Load(&prQ,hQ,0,xbOp_Optional))
			{
				if (m_pHdr->m_mainBlockId.m_handle == hQ.m_handle)
					xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::Check() : mainblock pointer invalid");
				else
					xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)+"')::Check() : next pointer invalid");
				bContinue = !bDisp;
				if (bDisp)
					nberr++;
				break;
			}
			xbMemLock	memLck(prQ);
			_xbSharedQ	*pQ = (_xbSharedQ*)memLck.GetPtr();
			if (pQ->m_hQueuePrev.m_handle != hQprev.m_handle)
			{
				xbRelOutput("ERROR: xbSharedQueue('"+xbString(m_filepath)
					+"')::Check() : previous pointer invalid (expected="+xbString(hQprev.m_handle,xbStringNum_hexa)
					+", cur="+xbString(pQ->m_hQueuePrev.m_handle,xbStringNum_hexa)+")");
				bContinue = !bDisp;
				if (bContinue)
					break;
				else
					nberr++;
			}
			hQprev = hQ;
			hQ = pQ->m_hQueueNext;

			if (bDisp)
			{
				xbRelOutput("INFO: xbSharedQueue('"+xbString(m_filepath)+"')::Check() : "+xbString(index)
					+": q name="+xbString(pQ->m_name)+", processId="+xbString(pQ->m_processId)+", lastAccess="+xbDateTime(pQ->m_lastAccess).ToString()
					+", this="+xbString(hQprev.m_handle,xbStringNum_hexa)
					+", next="+xbString(pQ->m_hQueueNext.m_handle,xbStringNum_hexa) 
					+", prev="+xbString(pQ->m_hQueuePrev.m_handle,xbStringNum_hexa));
			}
		}

		bDisp = true;
	}
	return nberr;
}
#pragma warning(pop)
