#ifndef _xbSHAREDQUEUE_
#define _xbSHAREDQUEUE_
/*<<<***************************************************************************
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.
***************************************************************************>>>*/

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#ifndef _xbSHAREDMEM_
#	include "xbSharedMem.h"
#endif
#ifndef _xbEXPR_
#	include "xbExpr.h"
#endif
#ifndef _xbDATETIME_
#	include "xbDateTime.h"
#endif

class __declspec(uuid("{CCAB7B8A-57C8-4a42-B24D-D17AD813773C}")) xbSharedQueue;

#define xbQTARGET_ALL			NULL
#define xbQTARGET_THIS			(LPCSTR)1
#define xbQTARGET_ALLANDTHIS	(LPCSTR)2

#define xbQTARGET_APPMAX		2000

struct _xbSharedMsg;
struct _xbSharedQ;
class xbSharedQueueEnum;
class xbEXPORT xbSharedQueue:public xbSharedHeap
{
public:
	xbSharedQueue(uint64 cByteMax,LPCSTR pFilePath = NULL,bool bCreate = false,ulong cByteLoadedMax = xbSHAREDHEAP_CBYTELOADEDMAX,ulong cByteSect = xbSHAREDHEAP_CBYTESECT,ulong cBytePage = xbSHAREDHEAP_CBYTEPAGE)
		:xbSharedHeap(cByteMax,pFilePath,false,cByteLoadedMax,cByteSect,cBytePage),
		m_qEvent(xbCtor_NoOp)
	{
		init();
		if (bCreate) Create();
	}
	xbSharedQueue(const xbSecurityAttr &attr,uint64 cByteMax,LPCSTR pFilePath = NULL,bool bCreate = false,ulong cByteLoadedMax = xbSHAREDHEAP_CBYTELOADEDMAX,ulong cByteSect = xbSHAREDHEAP_CBYTESECT,ulong cBytePage = xbSHAREDHEAP_CBYTEPAGE)
		:xbSharedHeap(attr,cByteMax,pFilePath,false,cByteLoadedMax,cByteSect,cBytePage),
		m_qEvent(xbCtor_NoOp)
	{
		init();
		if (bCreate) Create();
	}

	virtual ~xbSharedQueue()
	{
		eProtect(if (m_bCreated) Destroy());
	}

	xbImplObject();

	virtual bool GetInterface(REFIID riid, void ** ppInterf)
	{
		xbImplInterface(xbSharedQueue);
		xbImplInterface(xbSharedHeap);
		xbImplInterface(sIxbLock);
		return xbObject::GetInterface(riid,ppInterf);
	}

	virtual void Create();
	virtual void Destroy();
	virtual const GUID &GetFileID() const;

	virtual void SetQueueName(LPCSTR pQueueName);
	xbString GetQueueName() const 
	{
		xbLock lck(&m_mutex);
		xbString ret(m_qName);
		ret.OwnData();
		return ret;
	}
	
	virtual int Post(LPCSTR target,ulong msgId,const void *pData,int cByte,ulong wParam, ulong lParam);
	virtual int Post(LPCSTR target,ulong msgId,xbSharedMem *pMem,ulong wParam, ulong lParam);
	virtual int Post(LPCSTR target,ulong msgId,ulong wParam, ulong lParam)
	{
		return Post(target,msgId,NULL,wParam,lParam);
	}

	virtual bool Peek(ulong *pMsgId,xbRefPtr<xbSharedMem> *pprMem,ulong *pWparam,ulong *pLparam,bool bRemove = true);
	virtual bool Wait(bool *pbTimeOut = NULL,bool *pbCancel = NULL);
	virtual bool Wait(xbEvent &ev2,bool *pbTimeOut = NULL,bool *pbCancel = NULL);
	virtual bool Get(ulong *pMsgId,xbRefPtr<xbSharedMem> *pprMem,ulong *pWparam,ulong *pLparam)
	{
		for(;;)
		{
			if (Peek(pMsgId,pprMem,pWparam,pLparam))
				return true;
			if (!Wait())
				return false;
		}
	}
	virtual void Close();
	virtual void CancelClose();
	bool IsClosed() const;

	virtual bool Alloc(xbRefPtr<xbSharedMem> *pprMem,ulong cByte,xbOpMode opm =xbOp_Required); 
	virtual bool CleanQlist();

	void SetTimeOut(DWORD ti)
	{
		m_qEvent.SetTimeOut(ti);
	}
	DWORD GetTimeOut()
	{
		return m_qEvent.GetTimeOut();
	}

	bool post(xbSharedMem *pTarget,ulong msgId,xbSharedMem *pMem,ulong wParam, ulong lParam,ulong *pProcessToRetry);
	int post(xbArray<ulong> &processes,ulong msgId,xbSharedMem *pMem,ulong wParam, ulong lParam,xbArray<ulong> *pProcessesToRetry);

	virtual bool	EndMemLocks()
	{
		Close();
		return xbSharedHeap::EndMemLocks();
	}
	int Check();
protected:
	ulong					m_processId;
	xbRefPtr<xbSharedMem>	m_prQ;
	bool					m_bClosed;
	xbString				m_qName;

	void init();
	void deleteMsg(_xbSharedMsg *pMsg);
	void deleteQ(_xbSharedQ *pQ,bool bInChain,bool bDelChain);

	friend xbSharedQueueEnum;

public:
	xbEventEx				m_qEvent;
};

class xbEXPORT xbSharedQueueEnum:public xbExpr
{
public:
	xbSharedQueueEnum()
		:xbExpr(ExprMode(Search_Name))
	{
		m_excludeProcessId = 0;
		m_pParent = NULL;
		m_index = 0;
	}
	virtual ~xbSharedQueueEnum()
	{
		eProtect(Stop());
	}
	enum SearchMode
	{
		Search_Name=		0x00000001,
		Search_ProcessId=	0x00000002,

		Search_CaseDep=		Expr_CaseDep,

		//Predefined modes
		Search_All=			Expr_All
	};
	void Start(xbSharedQueue *pParent,bool bExcludeThisProcess = true)
	{
		Stop();
		m_pParent = pParent;
		m_excludeProcessId = bExcludeThisProcess?m_pParent->m_processId:0;
		m_index = 0;
	}
	void Stop()
	{
		m_lckqMutex.Unlock();
		m_prQ.Empty();
		m_excludeProcessId = 0;
		m_pParent = NULL;
	}
	xbString	GetQname() const;
	ulong		GetQprocess() const;
	xbDateTime		GetQlastAccess() const;

	xbSharedMem *getQptr()
	{
		if (m_prQ.IsEmpty())
			xbThrowEsys("xbSharedQueueEnum()::getQptr() : no current queue selected");
		return m_prQ;
	}
	int			GetQindex() const
	{
		return m_index;
	}
protected:
	//Overrided events
	virtual bool onGetNext();
	virtual bool onKeysOk(const Cond *pCond,ulong mode) const;
	virtual bool onFlagSet(bool bFirst,const xbString &str,int op,ulong *pmode) const;

	xbSharedQueue			*m_pParent;

	xbLock					m_lckqMutex;
	xbRefPtr<xbSharedMem>	m_prQ;
	ulong					m_excludeProcessId;
	int						m_index;
};

struct _xbSharedMsg
{
	/*000*/ ulong			m_msgId,m_wParam,m_lParam;
	/*012*/ xbSharedHandle	m_hData;
}; /*016*/

#define _xbSharedQ_SIZE	16
#ifdef _dbgMEM
struct __declspec(uuid("{EFF00FA8-09CB-4e29-A1DB-42943C07FBCB}"))
#else
struct __declspec(uuid("{38EA03EF-3783-4ff1-9099-1C6139D3217C}"))
#endif
	_xbSharedQ
{
//protected by queue own mutex
	/*000*/ _xbSharedMsg	m_msg[_xbSharedQ_SIZE];
	/*256*/ ulong			m_cMsgWaiting;
	/*260*/ ulong			m_processId;
	/*264*/ double			m_lastAccess;

//protected by sharedheap mutex
	/*272*/ xbSharedHandle	m_hQueuePrev;
	/*276*/ xbSharedHandle	m_hQueueNext;
	/*280*/ char			m_name[8];
};/*288*/


#endif
