/*  $Id: event_listener_win32.cpp,v 1.7 2004/02/01 03:07:16 mbn Exp $
**
**  ClanLib Game SDK
**  Copyright (C) 2003  The ClanLib Team
**  For a total list of contributers see the file CREDITS.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**  Lesser General Public License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
**
*/

#include "Core/precomp.h"
#include "event_listener_win32.h"
#include "event_trigger_win32.h"
#include "API/Core/System/system.h"

/////////////////////////////////////////////////////////////////////////////
// CL_EventListener_Win32 construction:

CL_EventListener_Win32::CL_EventListener_Win32(CL_EventListener *owner)
:
	CL_EventListener_Generic(owner)
{
}

CL_EventListener_Win32::~CL_EventListener_Win32()
{
}

/////////////////////////////////////////////////////////////////////////////
// CL_EventListener_Win32 implementation:

bool CL_EventListener_Win32::wait(int timeout)
{
	if (triggers.empty()) // no triggers, just do the sleep.
	{
		CL_System::sleep(timeout);
		return false;
	}

	int num_handles = triggers.size();
	HANDLE *handles = new HANDLE[num_handles];

	int i = 0;
	std::list< CL_SharedPtr<CL_EventTrigger_Generic> >::iterator it;
	for (it = triggers.begin(); it != triggers.end(); it++)
	{
		CL_EventTrigger_Win32 *trigger = static_cast<CL_EventTrigger_Win32*>((*it).get());
		handles[i++] = trigger->wait_handle;
	}

	DWORD result = WaitForMultipleObjects(
		num_handles,
		handles,
		FALSE,
		timeout == -1 ? INFINITE : timeout);

	delete[] handles;

	if (result == WAIT_TIMEOUT) return false;
	return true;
}
