/*
	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.
*/

#ifndef REFERENCED_OBJECT_H
#define REFERENCED_OBJECT_H

//=====================================================================================================================
//=====================================================================================================================

namespace Game
{
	//=================================================================================================================
	/// @brief		Base class for a reference counted managed object
	//=================================================================================================================

	class ReferencedObject
	{
		public:
			
			//=========================================================================================================
			// Functions
			//=========================================================================================================
			
				
				
				#ifdef DEBUG
				
					//=================================================================================================
					/// @brief		Debug only function: initialises the leak checking in debug.
					/// @remarks	This must be called before creating any reference counted objects in debug.
					//=================================================================================================
				
					static void DebugInit()
					{
						s_allocs = new std::set<ReferencedObject*>();
					}
				
				#endif
				
				#ifdef DEBUG
				
					//=================================================================================================
					/// @brief		Debug only function: shuts down the leak checking in debug and checks for leaks
					/// @post		There must be no memory leaks
					//=================================================================================================
					
					static void DebugShutdown()
					{
						// Make sure there are no leaks
					
						ENSURE( s_allocs->size() == 0 , "There must be no memory leaks" )
						
						// Delete this
						
						delete s_allocs; s_allocs = 0;
					}
				
				#endif

				/// Gets the number of references that are currently there to the object

				inline unsigned int GetReferenceCount(){ return m_reference_count; }
				
				//=====================================================================================================
				/// @brief		Creates the object
				/// @remarks	The reference count is always 1 for a newly created ReferencedObject.
				///				Be sure to call RemoveReference() at the source of creation once 
				///				you are finished with the object in that location.
				//=====================================================================================================

				inline ReferencedObject()
				{
					m_reference_count = 1;
					
					// In debug mode increment the static object reference count
					
					#if DEBUG
					
						s_object_count++;
						
					#endif
				}

				//=====================================================================================================
				/// @brief		Destroys the object
				//=====================================================================================================

				virtual inline ~ReferencedObject()
				{
					// Make sure the number of references is now zero
						
					ENSURE(m_reference_count==0,"Reference counted object can only be deleted when reference count is zero!");		
					
					// In debug mode decrement the static object reference count
					
					#if DEBUG
					
						s_object_count--;
						
					#endif	
				}

				//=====================================================================================================
				/// @brief		Add a reference to the object. You should do this if you are storing a reference to the 
				///				object for later use, since the object may be deleted on you!
				//=====================================================================================================

				inline void AddReference()
				{ 
					// Cannot add references to an already deleted object
					
					ENSURE(m_reference_count!=0,"Reference counted object has already been deleted!");
					
					// Increment the reference count

					m_reference_count++; 
					
					// In debug add it to the set of objects alloced:
					
					#ifdef DEBUG
					
						s_allocs->insert(this);
					
					#endif
				}

				//=====================================================================================================================
				/// @brief		Remove a reference to the object. Object will self delete when there are no references left.
				//=====================================================================================================================

				inline void RemoveReference()
				{ 
					// Make sure reference count is not zero 

					ENSURE(m_reference_count!=0,"Reference counted object has already been deleted!");

					// Remove the reference:
					
					m_reference_count--;
					
					// If the count is now zero then delete the object
					
					if ( m_reference_count == 0 )
					{
						// Remove from the set of allocs in debug
						
						#ifdef DEBUG
						
							s_allocs->erase(this);
						
						#endif
					
						// Delete thyself
					
						delete this;
					}
				}

				#ifdef DEBUG
				
					/// Debug only function. Gives the number of referenced objects in existance
					
					static inline unsigned GetGlobalObjectCount(){ return s_object_count; }
					
				#endif
				
		private:
			
			//=========================================================================================================
			// Variables
			//=========================================================================================================			
				
				/// Number of references there are currently to this object
				
				unsigned int m_reference_count;
				
				#ifdef DEBUG
				
					/// Debug only: a static count of the number of objects in existance. Used for crude leak testing.
					
					static unsigned s_object_count;
					
					/// Debug only: a gloabl set containing all allocs
					
					static std::set<ReferencedObject*> * s_allocs;

				#endif
	};
};

#endif
