/*
	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		Represents one participant in the networked architecture of the game. This is either a client or
///				a server. This basically encapuslates the network address of the peer as well as holding onto 
///				which objects the peer owns.
//=====================================================================================================================

#include "Precompiled.h"
#include "Game/GamePeer.h"
#include "Game/GamePacket.h"
#include "Game/GameSession.h"
#include "Game/GameFrameTimer.h"
#include "Game/GameNetSerializer.h"
#include "GameObjects/GameObjectBase.h"

using namespace Game;

//=====================================================================================================================
/// @brief		Creates the peer description:
/// @param		addr - network address of the peer
/// @param		session - the game session the peer belongs to
/// @param		peer_id - the id of the peer. This will be always zero for servers
/// @remarks	The given session object must remain valid whilst this object is in existance
/// @pre		The given address must be valid
/// @pre		The given session object cannot be null
//=====================================================================================================================

GamePeer::GamePeer( const NetworkAddress & addr , GameSession * session , unsigned peer_id )
{
	// Make sure ok:
	
	ENSURE( addr.IsValid()	, "The given session object must remain valid whilst this object is in existance"	)
	ENSURE( session			, "The given session object cannot be null"											)
	
	// Get current time:
	
	unsigned time = GetTickCount();
	
	// Save everything:
	
	m_session			= session;
	m_address			= addr;
	m_control_object	= 0;
	m_last_send_time	= time;
	m_last_recv_time	= time;
	m_peer_id			= peer_id;
}

//=====================================================================================================================
/// @brief		Destroys the peer description:
//=====================================================================================================================

GamePeer::~GamePeer()
{
	// If we have a conttrol object then remove the reference to it:
	
	if ( m_control_object )
	{
		m_control_object->RemoveReference();
	}

	// Clear the list of create and delete requests:
	
	{
		{
			std::list<CreateDeleteRequest>::iterator i = m_pending_create_requests.begin();
			std::list<CreateDeleteRequest>::iterator e = m_pending_create_requests.end();

			while ( i != e )
			{
				// Remove reference to this object and move on

				(*i).m_object->RemoveReference(); i++;
			}
		}

		{
			std::list<CreateDeleteRequest>::iterator i = m_pending_delete_requests.begin();
			std::list<CreateDeleteRequest>::iterator e = m_pending_delete_requests.end();

			while ( i != e )
			{
				// Remove reference to this object and move on

				(*i).m_object->RemoveReference(); i++;
			}
		}

		m_pending_create_requests.clear();
		m_pending_delete_requests.clear();
	}
}

//=====================================================================================================================
/// @brief		Sets which game object the peer 'owns'. This should always be null in the case of a server
/// @param		object - object we are now controlling
/// @remarks	This function will add a reference to the given object. Be sure to call SetControlObject(0) when done.
//=====================================================================================================================

void GamePeer::SetControlObject( GameObjectBase * object )
{
	// See if the object was given:
	
	if ( object ) object->AddReference();
	
	// Remove reference from the old object if there:
	
	if ( m_control_object ) m_control_object->RemoveReference();
	
	// Save:
	
	m_control_object = object;
}

//=====================================================================================================================
/// @brief		Tells if we should send a packet to the peer to keep the connection alive.
/// @returns	True if we should send a keepalive message
/// @remarks	If the time since the last send is greater than or equal to half the timeout value specified in the 
///				GameSession object, this function will return true.
//=====================================================================================================================

bool GamePeer::ShouldSendKeepalive() const
{
	// Get the current time:
	
	unsigned time = GetTickCount();
	
	// Get the time since the last send:
	
	unsigned since_send = time - m_last_send_time;
	
	// See if we should send:
	
	if ( since_send >= m_session->GetSettings().m_timeout_ms / 2 ) return true; else return false;
}

//=====================================================================================================================
/// @brief		Tells if the connection to the peer has timed out
/// @returns	True if the connection to the peer has timed out
//=====================================================================================================================

bool GamePeer::HasConnectionTimedOut() const
{
	// Get the current time:
	
	unsigned time = GetTickCount();
	
	// Get the time since the last send:
	
	unsigned since_recv = time - m_last_recv_time;
	
	// See if timeout:
	
	if ( since_recv >= m_session->GetSettings().m_timeout_ms ) 
	{
		return true;
	}
	else 
	{
		return false;
	}
}

//=====================================================================================================================
/// @brief		Server only function: makes a pending request to the client that the object be deleted on the 
///				client. This request is sent at a later stage.
/// @param		object - object we are adding a pending delete request to be transmitted to the client for
/// @pre		This must be called on the server
/// @pre		The given object must not already be in the delete object request queue
//=====================================================================================================================

void GamePeer::AddDeleteRequest( GameObjectBase & object )
{
	// Only allowed on the server

	ENSURE( m_session->IsServer() , "This must be called on the server" )

	// Can't be done twice:

	#ifdef DEBUG

		std::list<CreateDeleteRequest>::iterator i = m_pending_delete_requests.begin();
		std::list<CreateDeleteRequest>::iterator e = m_pending_delete_requests.end();

		while ( i != e )
		{
			// Get this object:

			GameObjectBase & cmp_obj = * ((*i).m_object);

			// Make sure it is not the same:

			ENSURE( object.GetNetId() != cmp_obj.GetNetId() , "The given object must not already be in the delete object request queue" )

			// Next object 

			i++;
		}

	#endif

	// Make a create delete request:

	CreateDeleteRequest request;

	request.m_object					= & object;
	request.m_time_till_retransmission	= 0;

	// Stick it into the queue

	m_pending_delete_requests.push_back(request);
	
	// Add a reference to the object:

	object.AddReference();
}

//=====================================================================================================================
/// @brief		Server only function: Acknowledges receipt of a delete request on the client, thus stops any 
///				retransmissions of that request to the client after the timeout has elapsed.
/// @param		net_id - network id of the object being acknowledged
/// @pre		This must be called on the server only
//=====================================================================================================================

void GamePeer::AcknowledgeDeleteRequest( unsigned net_id )
{
	// Only allowed on the server

	ENSURE( m_session->IsServer() , "This must be called on the server only" )

	// Run through all of the objects in the delete request queue:

	std::list<CreateDeleteRequest>::iterator i = m_pending_delete_requests.begin();
	std::list<CreateDeleteRequest>::iterator e = m_pending_delete_requests.end();

	while ( i != e )
	{
		// Get this request:

		CreateDeleteRequest request = * i;

		// See if the object matches:

		if ( request.m_object->GetNetId() == net_id )
		{
			// Remove the reference to this object:

			request.m_object->RemoveReference();

			// Remove this request

			m_pending_delete_requests.erase(i);

			// Done:

			break;
		}
		
		// Next request

		i++;
	}
}

//=====================================================================================================================
/// @brief		Server only function: makes a pending request to the client that the object be created on the 
///				client. This request is sent at a later stage.
/// @param		object - object we are adding a pending create request to be transmitted to the client for
/// @pre		This must be called on the server
/// @pre		The given object must not already be in the create object request queue
/// @pre		The given object must not be in the delete object request queue
//=====================================================================================================================

void GamePeer::AddCreateRequest( GameObjectBase & object )
{
	// Only allowed on the server

	ENSURE( m_session->IsServer() , "This must be called on the server" )

	// Can't create an object after it's been deleted!

	#ifdef DEBUG

	{
		std::list<CreateDeleteRequest>::iterator i = m_pending_delete_requests.begin();
		std::list<CreateDeleteRequest>::iterator e = m_pending_delete_requests.end();

		while ( i != e )
		{
			// Get this object:

			GameObjectBase & cmp_obj = * ((*i).m_object);

			// Make sure it is not the same:

			ENSURE( object.GetNetId() != cmp_obj.GetNetId() , "The given object must be in the delete object request queue" )

			// Next object 

			i++;
		}
	}

	#endif

	// Can't be done twice:

	#ifdef DEBUG

	{
		std::list<CreateDeleteRequest>::iterator i = m_pending_create_requests.begin();
		std::list<CreateDeleteRequest>::iterator e = m_pending_create_requests.end();

		while ( i != e )
		{
			// Get this object:

			GameObjectBase & cmp_obj = * ((*i).m_object);

			// Make sure it is not the same:

			ENSURE( object.GetNetId() != cmp_obj.GetNetId() , "The given object must not already be in the create object request queue" )

			// Next object 

			i++;
		}
	}

	#endif

	// Make a create delete request:

	CreateDeleteRequest request;

	request.m_object					= & object;
	request.m_time_till_retransmission	= 0;

	// Stick it into the queue

	m_pending_create_requests.push_back(request);
	
	// Add a reference to the object:

	object.AddReference();
}

//=====================================================================================================================
/// @brief		Server only function: Acknowledges receipt of a create request on the client, thus stops any 
///				retransmissions of that request to the client after the timeout has elapsed.
/// @param		net_id - network id of the object being acknowledged
//=====================================================================================================================

void GamePeer::AcknowledgeCreateRequest( unsigned net_id )
{
	// Only allowed on the server

	ENSURE( m_session->IsServer() , "This must be called on the server only" )

	// Run through all of the objects in the create request queue:

	std::list<CreateDeleteRequest>::iterator i = m_pending_create_requests.begin();
	std::list<CreateDeleteRequest>::iterator e = m_pending_create_requests.end();

	while ( i != e )
	{
		// Get this request:

		CreateDeleteRequest request = * i;

		// See if the object matches:

		if ( request.m_object->GetNetId() == net_id )
		{
			// Remove the reference to this object:

			request.m_object->RemoveReference();

			// Remove this request

			m_pending_create_requests.erase(i);

			// Done:

			break;
		}
		
		// Next request

		i++;
	}
}

//=====================================================================================================================
/// @brief		Transmits any create object requests that need to be transmitted to the client and puts
///				them into the given packet.
/// @param		p - packet to put the create object requests into
//=====================================================================================================================

void GamePeer::SendCreateRequests( GamePacket & p )
{
	// Run through the list of create requests:

	std::list<CreateDeleteRequest>::iterator i = m_pending_create_requests.begin();
	std::list<CreateDeleteRequest>::iterator e = m_pending_create_requests.end();

	while ( i != e )
	{
		// Get this request:

		CreateDeleteRequest & request = * i;

		// Decrement frame interval:

		request.m_time_till_retransmission -= GameFrameTimer::FRAME_INTERVAL_MS;

		// See if time to retransmit:

		if ( request.m_time_till_retransmission <= 0 )
		{
			// Pack this object:

			GameNetSerializer::Pack(*request.m_object,p);

			// Reset time till next re-transmission:

			request.m_time_till_retransmission += m_session->GetSettings().m_reliable_timeout_ms;
		}

		// Next request:

		i++;
	}
}

//=====================================================================================================================
/// @brief		Transmits any delete object requests that need to be transmitted to the client and puts
///				them into the given packet.
/// @param		p - packet to put the delete object requests into
//=====================================================================================================================

void GamePeer::SendDeleteRequests( GamePacket & p )
{
	// Run through the list of create requests:

	std::list<CreateDeleteRequest>::iterator i = m_pending_delete_requests.begin();
	std::list<CreateDeleteRequest>::iterator e = m_pending_delete_requests.end();

	while ( i != e )
	{
		// Get this request:

		CreateDeleteRequest & request = * i;

		// Decrement frame interval:

		request.m_time_till_retransmission -= GameFrameTimer::FRAME_INTERVAL_MS;

		// See if time to retransmit:

		if ( request.m_time_till_retransmission <= 0 )
		{
			// Put the request into the packet:

			p.WriteChunkId( GamePacketChunk::PKCKID_DELETE );
			p.WritePackedUint( request.m_object->GetNetId() );

			// Reset time till next re-transmission:

			request.m_time_till_retransmission += m_session->GetSettings().m_reliable_timeout_ms;
		}

		// Next request:

		i++;
	}
}
