/*
	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 thread. This particular thread object 
//=====================================================================================================================

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

using namespace Game;

//=====================================================================================================================
/// @brief		Creates the thread.
/// @param		thread_main - the main function for the thread, or where it begins execution
/// @param		stack_size - size of the thread's stack. specify zero to let the system decide on stack size.
/// @param		exit_on_failure - true if the program should issue a fatal error upon failure to create the thread
/// @pre		Thread entry function must not be null
//=====================================================================================================================

Thread::Thread
( 
	ThreadEntryFunction		thread_main		, 
	unsigned				stack_size		,
	bool					exit_on_failure	
)
{
	// Make sure ok

	ENSURE( thread_main , "Thread entry function must not be null" )
	
	// Clear the thread user data
	
	m_user_data = 0;
	
	// Save entry function
	
	m_entry_function = thread_main;
	
	// Set the id of the thread that made this thread
	
	#ifdef DEBUG
	
		m_creator_id = GetCurrentThreadId();
		
	#endif
	
	// Don't exit:
	
	m_exit_common_entry_function = false;
	
	// Try and make the thread:
	
	m_thread_handle = CreateThread(0,stack_size,CommonThreadEntryPoint,this,CREATE_SUSPENDED,&m_thread_id);
	
	// See if that failed:
	
	if ( m_thread_handle == 0 )
	{
		// See if we are to issue a fatal error:
		
		if ( exit_on_failure )
		{
			// Issue a fatal error:
			
			Errors::IssueError("Unable to create a required worker thread. Now exiting.");
		}
		
		// Invalid conditions:
		
		m_thread_ended_condition	= 0;
		m_begin_thread_condition	= 0;	
	}
	else
	{
		// Make our conditions if we are valid:
	
		m_thread_ended_condition = new Condition(true,exit_on_failure);
		
		// See if that failed:
		
		if ( m_thread_ended_condition->IsValid() == false )
		{
			// Destroy:
			
			delete m_thread_ended_condition;
			
			// Clear both conditions
			
			m_thread_ended_condition	= 0;
			m_begin_thread_condition	= 0;
			
			// We are invalid:
			
			CloseHandle(m_thread_handle); m_thread_handle = 0;
		}
		else
		{
			// Make the begin thread condition
			
			m_begin_thread_condition = new Condition(false,exit_on_failure);
			
			// See if that succeded:
			
			if ( m_begin_thread_condition->IsValid() == false )
			{
				// Destroy both created conditions:
				
				delete m_thread_ended_condition; m_thread_ended_condition = 0;
				delete m_begin_thread_condition; m_begin_thread_condition = 0;
					
				// We are invalid:
				
				CloseHandle(m_thread_handle); m_thread_handle = 0;					
			}
			else
			{
				// Success! Resume our created thread if we can
				
				DWORD result = ResumeThread(m_thread_handle);
				
				// If that failed then see if we have to issue an error:
				
				if ( result == (DWORD)(-1) )
				{
					// See if we are to abort on a failure
					
					if ( exit_on_failure )
					{
						Errors::IssueError("Unable to begin/resume a required worker thread. Now exiting.");
					}
					else
					{
						// Otherwise cleanup up everything and ignore:
						
						delete m_thread_ended_condition; m_thread_ended_condition = 0;
						delete m_begin_thread_condition; m_begin_thread_condition = 0;
							
						// We are invalid:
						
						CloseHandle(m_thread_handle); m_thread_handle = 0;							
					}
										
				}
				
			}	// end else of if ( m_begin_thread_condition->IsValid() == false )
			
		}	// end else of if ( m_thread_ended_condition->IsValid() == false )
		
	}	// end else of if ( thread_handle == 0 )
	
}

//=====================================================================================================================
/// @brief		Destroys the thread
/// @pre		The caller must be the thread that made this thread
/// @remarks	This function waits until the thread has finished, a thread cannot be forcibly terminated as this 
///				might result in a memory leak.
//=====================================================================================================================

Thread::~Thread()
{
	// Make sure ok:

	ENSURE( GetCurrentThreadId() == m_creator_id , "The caller must be the thread that made this thread" )

	// Only if valid:
	
	if ( IsValid() )
	{
		// Don't continue re-executing the thread:
		
		m_exit_common_entry_function = true;	
	
		// Wait until the thread is finished:
		
		WaitTillFinished();
		
		// Begin executing the thread so it can exit the CommonThreadEntryPoint() function
		
		m_begin_thread_condition->SetTrue();
		
		// Wait until the thread has been terminated completely:
		
		WaitForSingleObject( m_thread_handle , INFINITE );
		
		// Release our thread
		
		CloseHandle( m_thread_handle );
		
		// Delete the conditions:
		
		delete m_begin_thread_condition;
		delete m_thread_ended_condition;
	}
}

//=====================================================================================================================
/// @brief		Begins running the thread
/// @param		user_data - user data that is to be passed to the thread entry function
/// @pre		The thread must be valid
/// @pre		The thread must not already be running
/// @pre		The caller must be the thread that made this thread
/// @pre		The previous suspend count of the thread must be 1
//=====================================================================================================================

void Thread::Run( void * user_data )
{
	ENSURE( IsValid()								, "The thread must be valid"							)
	ENSURE( IsRunning() == false					, "The thread must not already be running"				)
	ENSURE( GetCurrentThreadId() == m_creator_id	, "The caller must be the thread that made this thread"	)
	
	// The thread has not ended:
	
	m_thread_ended_condition->SetFalse();
	
	// Set the user data for the thread
	
	m_user_data = user_data;
	
	// Begin running another iteration of the thread:
	
	m_begin_thread_condition->SetTrue();
}

//=====================================================================================================================
/// @brief		Tells if the thread is currently running
/// @returns	True if the thread is running
/// @pre		The thread must be valid
/// @pre		The caller must be the thread that made this thread
//=====================================================================================================================

bool Thread::IsRunning() const
{
	// Make sure ok:

	ENSURE( IsValid()								, "The thread must be valid"							)
	ENSURE( GetCurrentThreadId() == m_creator_id	, "The caller must be the thread that made this thread"	)
	
	// See if the thread finished condition is false:
	
	return m_thread_ended_condition->IsFalse();
}

//=====================================================================================================================
/// @brief		Waits until the thread has finished excecution
/// @pre		The thread must be valid
/// @pre		The caller must be the thread that made this thread
//=====================================================================================================================

void Thread::WaitTillFinished() const
{
	ENSURE( IsValid()								, "The thread must be valid"							)
	ENSURE( GetCurrentThreadId() == m_creator_id	, "The caller must be the thread that made this thread"	)
	
	/// Wait until the thread finished condition is true
	
	m_thread_ended_condition->WaitUntilTrue();
}

//=====================================================================================================================
/// @brief		This is the initial thread entry function used for all threads the void * parameter points to a 
///				thread object.
/// @param		param - void * pointer that points to the thread that is entering this function
/// @returns	An error code indicating success or failure of the thread
/// @pre		The given parameter must not be null
//=====================================================================================================================

DWORD WINAPI Thread::CommonThreadEntryPoint( void * param )
{
	// Make sure ok:
	
	ENSURE( param != 0	, "The given parameter must not be null" )
	
	// Get the thread:
	
	Thread * thread = (Thread*)(param);
	
	// See if we are to exit:
	
	while ( thread->m_exit_common_entry_function == false )
	{	
		// Wait for to the signal to begin:
		
		thread->m_begin_thread_condition->WaitUntilTrue();
		
		// Don't do another loop until told to do so:
		
		thread->m_begin_thread_condition->SetFalse();
	
		// Need to recheck this: may have changed since the thread was waiting for the signal to begin
		
		if ( thread->m_exit_common_entry_function == false )
		{	
			// Call the thread entry function:
			
			thread->m_entry_function(thread->m_user_data);
		}
		
		// We have finished executing
		
		thread->m_thread_ended_condition->SetTrue();
	}

	// Success:
	
	return 0;
}
