/*
	Lan Wars.
	Copyright (c) 2009, Darragh Coy.
	All rights reserved.
	Original work(s), source code & author(s) details available at: http://www.darraghcoy.com

	Redistribution and use in source and binary forms, with or without modification, are permitted 
	provided that the following conditions are met:

		* 	Redistributions of source code must retain the above copyright notice, this list of 
			conditions and the following disclaimer.
		* 	Redistributions in binary form must reproduce the above copyright notice, this list of 
			conditions and the following disclaimer in the documentation.
		* 	Neither the name of the author nor the names of contributors may be used to endorse or 
			promote products derived from this software without specific prior written permission.
		* 	The use of any third party libraries, modules or data files provided with the source 
			form of the program must follow and respect the individual licensing terms of these 
			components. You do not have permission to modify or circumvent the licensing terms for 
			provided third party components unless the third party licenses specifically allow this. 
			If you do not agree to the terms of provided third party components then you do not have 
			permission to use them in your derived work(s).
		* 	The terms of this license do not apply to separate (but related) distributions if supplied 
			by the author(s), only to the contents of this source distribution, derived works, and the 
			binaries produced by either modified or unmodified versions of the source code. The terms 
			of this license do not also apply to any third party libraries or components provided with 
			the source distribution. Such third party elements are licensed under their own separate 
			agreements.

	THIS SOFTWARE IS PROVIDED BY DARRAGH COY ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
	ARE DISCLAIMED. IN NO EVENT SHALL DARRAGH COY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
	OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
	OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
	IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//=====================================================================================================================
/// @brief		This class represents a condition that can be used to synchronise threads waiting for some condition
///				to be true. The event represents some global condition that is either true or false and differs
///				from a mutex in that there is no concept of ownership, the condition is either true or it is false.
/// @remarks	Although the condition can be modified by any thread, only the thread that created the condition is 
///				allowed to delete it. This follows the master-thread model of the Thread class. The master 
///				thread should create these conditions and all other sub threads should just use them.
//=====================================================================================================================

#include "Precompiled.h"
#include "Base\Threading\Condition.h"

using namespace Game;

//=====================================================================================================================
/// @brief		Creates the condition
/// @param		initially_true - whether the condition is initially true or not
/// @param		exit_on_failure - whether to exit if the condition cannot be created with the system
//=====================================================================================================================

Condition::Condition( bool initially_true , bool exit_on_failure )
{
	// Set the owner of this condition in debug
	
	#ifdef DEBUG
	
		m_owner_thread_id = GetCurrentThreadId();
	
	#endif

	// Create the event:
	
	m_event_handle = CreateEvent
	(
		0						,	// no security attributes
		TRUE					,	// manually set the condition
		(BOOL) initially_true	,	// if true then the event is initially signalled
		0							// not named
	);
	
	// See if that was ok:
	
	if ( m_event_handle == 0 )
	{
		// See if we are to exit on failure
		
		if ( exit_on_failure )
		{
			// Issue a fatal error:
			
			Errors::IssueError("Unable to create a required synchronisation event. Now exiting.");
		}
	}
}

//=====================================================================================================================
/// @brief		Destroys the condition
/// @pre		The thread that destroys this condition must be the thread that created it
//=====================================================================================================================

Condition::~Condition()
{
	// Make sure ok:
	
	ENSURE( GetCurrentThreadId() == m_owner_thread_id , "The thread that destroys this condition must be the thread that created it" )
	
	// Only if valid:
	
	if ( IsValid() )
	{	
		// Release our event handle:
		
		CloseHandle(m_event_handle);
	}
}

//=====================================================================================================================
/// @brief		Waits for the condition to be true. 
/// @pre		The condition must be valid
/// @post		The condition must be true upon the wait finishing
//=====================================================================================================================

void Condition::WaitUntilTrue() const
{
	// Make sure ok:
	
	ENSURE( IsValid() , "The condition must be valid" )
	
	#ifdef DEBUG

		// Wait:
		
		DWORD result = WaitForSingleObject(m_event_handle,INFINITE);
		
		// Make sure ok:
		
		ENSURE( result == WAIT_OBJECT_0 , "The condition must be true upon the wait finishing" )
	
	#else
	
		// Wait:
		
		WaitForSingleObject(m_event_handle,INFINITE);
	
	#endif
}

//=====================================================================================================================
/// @brief		Sets the condition to be true
/// @pre		The condition must be valid
/// @post		The condition must have been set to true
//=====================================================================================================================

void Condition::SetTrue()
{
	// Make sure ok:
	
	ENSURE( IsValid() , "The condition must be valid" )
	
	#ifdef DEBUG
	
		// Set the condition:
		
		BOOL result = SetEvent(m_event_handle);	
		
		// Make sure ok:
		
		ENSURE( result != FALSE , "The condition must have been set to true" )
	
	#else
	
		// Set the condition:
		
		SetEvent(m_event_handle);
	
	#endif
}

//=====================================================================================================================
/// @brief		Sets the condition to be false
/// @pre		The condition must be valid
/// @post		The condition must have been set to false
//=====================================================================================================================

void Condition::SetFalse()
{
	// Make sure ok:
	
	ENSURE( IsValid() , "The condition must be valid" )
	
	#ifdef DEBUG
	
		// Unset the condition:
		
		BOOL result = ResetEvent(m_event_handle);	
		
		// Make sure ok:
		
		ENSURE( result != FALSE , "The condition must have been set to false" )		
	
	#else
	
		// Unset the condition:
		
		ResetEvent(m_event_handle);		
	
	#endif
}

//=====================================================================================================================
/// @brief		Tells if the condition is true
/// @returns	True if the condition is true
/// @pre		The condition must be valid
/// @post		The value of the condition must have been successfully retrieved
//=====================================================================================================================

bool Condition::IsTrue() const
{
	// Make sure ok:
	
	ENSURE( IsValid() , "The condition must be valid" )
	
	// Get the event state:
	
	DWORD result = WaitForSingleObject( m_event_handle , 0 );
	
	// Make sure ok:
	
	ENSURE( result != 0xffffffff , "The value of the condition must have been successfully retrieved" )
	
	// Return if true or not:
	
	return result == WAIT_OBJECT_0;
}

//=====================================================================================================================
/// @brief		Tells if the condition is false
/// @returns	True if the condition is false
/// @pre		The condition must be valid
/// @post		The value of the condition must have been successfully retrieved
//=====================================================================================================================

bool Condition::IsFalse() const
{
	// Make sure ok:
	
	ENSURE( IsValid() , "The condition must be valid" )
	
	// Get the event state:
	
	DWORD result = WaitForSingleObject( m_event_handle , 0 );
	
	// Make sure ok:
	
	ENSURE( result != 0xffffffff , "The value of the condition must have been successfully retrieved" )
	
	// Return if false or not:
	
	return result != WAIT_OBJECT_0;	
}
