/*
	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 mutex, which is a synchronisation object that can be only held by one 
///				thread at a time.
//=====================================================================================================================

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

using namespace Game;

//=====================================================================================================================
/// @brief		Creates the mutex
/// @param		initial_owner - true if this thread should aquire ownership of
///				this mutex. This is equivalent to an automatic call to Lock()
/// @param		exit_on_failure - if true then the application will issue a fatal error
///				and exit if the mutex cannot be created. The mutex creation will thus be regarded
///				as a critically important operation.
//=====================================================================================================================

Mutex::Mutex( bool initial_owner , bool exit_on_failure )
{
	// Try and make the mutex

	m_mutex_handle = CreateMutex
	(
		0						,	// no security attributes
		(BOOL) initial_owner	,	// if we are to own the mutex initially
		0							// no name
	);

	// See if successful:

	if ( m_mutex_handle == 0 )
	{
		// Failed: if this was a critical operation then exit

		if ( exit_on_failure )
		{
			Errors::IssueError("Unable to create multi-threaded synchronisation mutex.");
		}

		// Debug only:

		#ifdef DEBUG

			m_owner_thread_id = 0xffffffff;

		#endif
	}

	// Debug only stuff:

	#ifdef DEBUG

		else
		{
			// See if this thread is an initial owner:

			if ( initial_owner )
			{
				m_owner_thread_id = GetCurrentThreadId();
			}
			else
			{
				m_owner_thread_id = 0xfffffff;
			}
		}

	#endif
}

//=====================================================================================================================
/// @brief		Destroys the mutex
/// @pre		The mutex must not be locked
//=====================================================================================================================

Mutex::~Mutex()
{
	// See if valid:

	if ( IsValid() )
	{
		// Make sure not locked:

		ENSURE( IsLocked() == false , "The mutex must not be locked" )

		// Release the mutex handle:

		CloseHandle(m_mutex_handle);
	}
}

//=====================================================================================================================
/// @brief		Locks the mutex, accquires ownership of the mutex by this thread or waits till free
/// @pre		The mutex should be valid
/// @pre		The mutex should not already be held by this thread
/// @post		The mutex should be accquired by the thread and it should not have been abandoned by another
/// @post		The mutex should not have been abandoned by another thread
//=====================================================================================================================

void Mutex::Lock()
{
	// Make sure ok:

	ENSURE( IsValid()									, "The mutex should be valid"								)
	ENSURE( GetCurrentThreadId() != m_owner_thread_id	, "The mutex should not already be held by this thread"		)

	// Wait for the mutex:

	#ifdef DEBUG

		// Wait

		DWORD result = WaitForSingleObject( m_mutex_handle , INFINITE );

		// Make sure that it never goes wrong

		ENSURE( result == WAIT_OBJECT_0 , "The mutex should be accquired by the thread and it should not have been abandoned by another" )

	#else

		// Wait

		WaitForSingleObject( m_mutex_handle , INFINITE );

	#endif

	#ifdef DEBUG

		// This thread now owns the mutex

		m_owner_thread_id = GetCurrentThreadId();

	#endif
}

//=====================================================================================================================
/// @brief		Frees the mutex, releases this threads hold on the mutex
/// @pre		The mutex should be valid
/// @pre		This thread should have ownership of the mutex
/// @post		The unlock operation should be successful
//=====================================================================================================================

void Mutex::Unlock()
{
	// Make sure ok:

	ENSURE( IsValid()									, "The mutex should be valid"						)
	ENSURE( m_owner_thread_id == GetCurrentThreadId()	, "This thread should have ownership of the mutex"	)

	#ifdef DEBUG
	
		// This thread does not own the lock anymore:
		
		m_owner_thread_id = 0xffffffff;

		// Release ownership of the mutex

		BOOL success = ReleaseMutex( m_mutex_handle );

		// Make sure that succeeded:

		ENSURE( success != 0 , "The unlock operation should be successful" )

	#else

		// Release ownership of the mutex

		ReleaseMutex( m_mutex_handle );

	#endif
}

//=====================================================================================================================
/// @brief		Tells if this mutex is held by another thread
/// @returns	Whether or not the mutex is currently held or not
/// @pre		The mutex should be valid
/// @pre		The mutex should not have been abandoned by a thread
/// @post		The check operation should have been successful
//=====================================================================================================================

bool Mutex::IsLocked()
{
	// Make sure ok:

	ENSURE( IsValid() , "The mutex should be valid" )	

	// Check the status of the mutex and return immediately:

	DWORD result = WaitForSingleObject( m_mutex_handle , 0 );

	// In debug make sure there is no error:

	ENSURE( result != WAIT_FAILED		, "The check operation should have been successful"			)
	ENSURE( result != WAIT_ABANDONED	, "The mutex should not have been abandoned by a thread"	)

	// See if the mutex is signalled:

	if ( result == WAIT_OBJECT_0 )
	{
		// Not locked:

		return false;
	}
	else
	{
		// Locked 

		return true;
	}
}
