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

#include "xbSync.h"
#include "xbMsg.h"
#include "xbException.h"
#include "xbSecurity.h"

bool xbMutex::Create(const xbSecurityAttr *pAttr,LPCSTR pName)
{
	if (m_hMutex != NULL)
		xbThrowEsys("xbMutex::Create("+xbString(pName?pName:"mutex with no name")+") : already created");
	if (pName && *pName == 0) pName = NULL;
	xbString _name;
	if (pName)
	{
		_name = xbString("Global\\") + pName;
		pName = _name;
	}
	m_hMutex = CreateMutex(pAttr?pAttr->Ptr():NULL,FALSE,pName);
	if (m_hMutex == NULL)
		xbThrowEsys(xbHR_LAST,"xbMutex::Create("+xbString(pName?pName:"mutex with no name")+") : failure");
	return ::GetLastError() != ERROR_ALREADY_EXISTS;
}

void xbMutex::Destroy()
{
	if (m_hMutex == NULL) return;
	HANDLE hMutex = Detach();
	::CloseHandle(hMutex);
}

void xbMutex::Lock() const
{
	if (m_hMutex == NULL) xbThrowEsys("xbMutex::Lock() : mutex not created");
	int cnt = 0;
	for(;;)
	{
		DWORD ret = ::WaitForSingleObject(m_hMutex,m_timeout);
		if (ret == WAIT_OBJECT_0) 
			return;
		if (ret == WAIT_TIMEOUT)
			xbThrowEsys(xbHR_TIMEOUT,"xbMutex::Lock() : timeout");
		if (ret == WAIT_ABANDONED)
		{
			xbRelOutput("xbMutex::Lock() : wait abandoned, retry, try cnt="+xbString(cnt));
			if (++cnt < 10)
			{
				::ReleaseMutex(m_hMutex);
				continue;
			}
			xbThrowEsys(E_ABORT,"xbMutex::Lock() : thread terminated");
		}
		break;
	}
	
	xbThrowEsys(xbHR_LAST,"xbMutex::Lock() : wait failure");
}

void xbMutex::Unlock() const
{
	if (m_hMutex == NULL) xbThrowEsys("xbMutex::Lock() : mutex not created");
	::ReleaseMutex(m_hMutex);
}

bool xbEvent::Create(const xbSecurityAttr *pAttr,LPCSTR pName,xbEventMode mode)
{
	if (m_hEvent != NULL)
		xbThrowEsys("xbEvent::Create("+xbString(pName?pName:"event with no name")+") : already created");
	
	if (pName && *pName == 0) pName = NULL;
	xbString _name;
	if (pName)
	{
		_name = xbString("Global\\") + pName;
		pName = _name;
	}

	m_hEvent = CreateEvent(pAttr?pAttr->Ptr():NULL,
		(mode == xbEventManual || mode == xbEventManualSet)?TRUE:FALSE,
		(mode == xbEventAutoSet || mode == xbEventManualSet)?TRUE:FALSE,
		pName);
	if (m_hEvent == NULL)
		xbThrowEsys(xbHR_LAST,"xbEvent::Create("+xbString(pName?pName:"event with no name")+") : failure");
	return ::GetLastError() != ERROR_ALREADY_EXISTS;
}

void xbEvent::Destroy()
{
	if (m_hEvent == NULL) return;
	HANDLE hEvent = Detach();
	::CloseHandle(hEvent);
}

bool xbEvent::wait(ulong timeOut,bool *pbCancel,bool bProcessMsg)
{
	if (m_hEvent == NULL) 
		xbThrowEsys("xbEvent::Wait() : event not created");
	DWORD ret;
//	bProcessMsg = false;//dbg
	if (bProcessMsg)
		ret = ::MsgWaitForMultipleObjectsEx(1,&m_hEvent,timeOut,xbWAITMSG_FILTER,xbWAITMSG_MODE);
	else
		ret = ::WaitForSingleObjectEx(m_hEvent,timeOut,TRUE);
	if (bProcessMsg
		&& ret == WAIT_OBJECT_0+1)
	{
		xbDoEvents(NULL);
		return 0;
	}
	if (ret == WAIT_OBJECT_0)
	{
		if (pbCancel) *pbCancel = false;
		return true;
	}
	if (ret == WAIT_IO_COMPLETION)
	{
		if (pbCancel) *pbCancel = false;
		return false;
	}
	if (ret == WAIT_ABANDONED)
	{
		if (!pbCancel)
			xbThrow xbEuser(E_ABORT,"Process/Application in destruction", "xbEvent::Wait() : wait abandoned");
		*pbCancel = true;
		return false;
	}
	if (ret == WAIT_TIMEOUT)
	{
		if (pbCancel) *pbCancel = false;
		return false;
	}
	xbThrowEsys(xbHR_LAST,"xbDownloadCenter::threadWaitForNewTask() : wait failure");
	return false;
}

bool xbEvent::wait(xbEvent &ev2,ulong timeOut,bool *pbCancel,bool bProcessMsg)
{
	if (m_hEvent == NULL) 
		xbThrowEsys("xbEvent::Wait() : event not created");
	DWORD ret;
//	bProcessMsg = false;//dbg
	HANDLE	arrEv[2] = {m_hEvent,ev2.GetHandle()};
	if (bProcessMsg)
		ret = ::MsgWaitForMultipleObjectsEx(2,arrEv,timeOut,xbWAITMSG_FILTER,xbWAITMSG_MODE);
	else
		ret = ::WaitForMultipleObjectsEx(2,arrEv,FALSE,timeOut,TRUE);
	if (bProcessMsg
		&& ret == WAIT_OBJECT_0+2)
	{
		xbDoEvents(NULL);
		return 0;
	}
	if (ret == WAIT_OBJECT_0 || ret == WAIT_OBJECT_0+1)
	{
		if (pbCancel) *pbCancel = false;
		return true;
	}
	if (ret == WAIT_IO_COMPLETION)
	{
		if (pbCancel) *pbCancel = false;
		return false;
	}
	if (ret == WAIT_ABANDONED)
	{
		if (!pbCancel)
			xbThrow xbEuser(E_ABORT,"Process/Application in destruction", "xbEvent::Wait() : wait abandoned");
		*pbCancel = true;
		return false;
	}
	if (ret == WAIT_TIMEOUT)
	{
		if (pbCancel) *pbCancel = false;
		return false;
	}
	xbThrowEsys(xbHR_LAST,"xbDownloadCenter::threadWaitForNewTask() : wait failure");
	return false;
}

bool xbEventEx::Wait(bool *pbCancel,bool bProcessMsg)
{
	return xbEvent::wait(m_timeout,pbCancel,bProcessMsg);
}

int	xbWait(long timeout,HANDLE *pEv,int cEv,bool bProcessMsg)
{
	if (timeout < 0)
		timeout = INFINITE;
	DWORD ret;
//	bProcessMsg = false;//dbg
	for(;;)
	{
		if (bProcessMsg)
			ret = ::MsgWaitForMultipleObjectsEx(cEv,pEv,timeout,xbWAITMSG_FILTER,xbWAITMSG_MODE);
		else
			ret = ::WaitForMultipleObjectsEx(cEv,pEv,FALSE,timeout,xbWAITSLEEP_ALERTABLE);

		if (bProcessMsg
			&& ret >= WAIT_OBJECT_0 + DWORD(cEv)
			&& ret < WAIT_OBJECT_0 + MAXIMUM_WAIT_OBJECTS)
		{
			xbDoEvents(NULL);
			return 0;
		}
		break;
	}
	if (ret >= WAIT_OBJECT_0 && ret < WAIT_OBJECT_0 + DWORD(cEv))
		return int(ret - WAIT_OBJECT_0) + 1;
		//Close
	if (ret == WAIT_TIMEOUT)
	{
//		xbDbgOutput("xbWait(): timeout");
		return -1;
	}
	if (ret == WAIT_IO_COMPLETION)
	{
//		xbDbgOutput("xbWait(): io completion");
		return -2;
	}
	if (ret == WAIT_ABANDONED)
		xbThrow xbEuser(E_ABORT,"Process/Application in destruction", "xbWait() : wait abandoned");
	xbThrowEsys(xbHR_LAST,"xbWait() : wait failure (ret="+xbString(ret)+")");
	return -1;
}

ulong xbWaitProcessEndExt(HANDLE hProcess,int millisecWaitTime,bool bProcessMsg)
{
	for(;;)
	{
		ulong exitcode;
		if (!::GetExitCodeProcess(hProcess,&exitcode))
			xbThrowEsys(xbHR_LAST,"xbWaitProcessEnd() failure");
		if (exitcode != STILL_ACTIVE) 
			return exitcode;

		if (millisecWaitTime != INFINITE && millisecWaitTime <= 0)
			xbThrowEsys(xbHR_TIMEOUT,"xbWaitProcessEnd() timeout");

		ulong tiStart = ::GetTickCount();
		::xbWait(millisecWaitTime,hProcess,bProcessMsg);
		if (millisecWaitTime == INFINITE)
			continue;
		ulong tiEnd = ::GetTickCount();
		millisecWaitTime -= int(xbDiffTime(tiEnd,tiStart));
	}
}

ulong xbWaitProcessEnd(HANDLE hProcess,int millisecWaitTime) // impl in xbSync.h
{
	return xbWaitProcessEndExt(hProcess,millisecWaitTime,true);
}

void	xbEXPORT xbSleep(ulong timeout)
{
	int64 startTime = -1;
	for(;;)
	{
		ulong ti = ::GetTickCount();
		if (startTime < 0) startTime = ti;
		else if (timeout != -1)
		{
			ulong diff = xbDiffTime(ti,ulong(startTime));
			if (diff > timeout)
				break;
			timeout -= diff;
		}
		int ret = ::MsgWaitForMultipleObjectsEx(0,NULL,timeout,xbWAITMSG_FILTER,xbWAITMSG_MODE);
		if (ret == WAIT_TIMEOUT)
			break;
		if (ret == WAIT_FAILED)
			xbThrowEsys(xbHR_LAST,"xbSleep() : wait failure");
		if (ret == WAIT_IO_COMPLETION)
			continue;

		xbDoEvents(NULL);
	}
}
