/*
	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 object is a box of health in the game world.
//=====================================================================================================================

#include "Precompiled.h"
#include "GameObjects/GameHealth.h"
#include "GameObjects/GamePlayer.h"
#include "GameObjects/GameMap.h"
#include "GameObjects/GameTeleportCloud.h"
#include "Game/GameCore.h"
#include "Game/GameSpriteBank.h"
#include "Game/GameObjectManager.h"
#include "Graphics/SpriteAnimation.h"
#include "Graphics/SpriteRenderer.h"
#include "Graphics/Camera3D.h"
#include "Doom/DoomLevel.h"
#include "Doom/DoomSector.h"
#include "Doom/DoomGLSubsectorV2.h"

using namespace Game;

//=====================================================================================================================
// Constants
//=====================================================================================================================

/// This is the height of the pickup off the floor

const float GameHealth::FLOOR_HEIGHT = 12;

/// Time in between respawns:

const float GameHealth::RESPAWN_TIME = 10.0f;

/// Distance at which we can be picked up at

const float GameHealth::PICKUP_RADIUS = 48.0f;

//=====================================================================================================================
/// @brief		Constructor. Creates the health object.
/// @param		position - position of the health box on the xz axes
/// @param		net_id - network id of the health box
/// @pre		GameCore must exist
/// @pre		GameCore must have a GameSpriteBank
//=====================================================================================================================

GameHealth::GameHealth( const Vec2f & xz_position , unsigned net_id ) 
: 
PositionalObject(Vec3f::Zero(),NetObject::OWNER_ID_NONE,net_id)
{
	// Need to figure out our y position in the level
	
	float y_pos = 0;
	
	{
		// Get our subsector in the level:
		
		const DoomGLSubsectorV2 * subsector = GameMap::GetSingleton().GetLevel().GetSubsector(xz_position);
		
		// Get our sector:
	
		if ( subsector )
		{
			const DoomSector & sector = GameMap::GetSingleton().GetLevel().GetSector(*subsector);
			
			// Get our y position:
			
			y_pos = sector.m_floor_y + FLOOR_HEIGHT;
		}
	}
	
	// Save our position:
	
	SetPosition( Vec3f(xz_position.x,y_pos,xz_position.y) );

	// Make sure ok
	
	ENSURE( GameCore::GetSingleton()					, "GameCore must exist"					)
	ENSURE( GameCore::GetSingleton()->GetSpriteBank()	, "GameCore must have a GameSpriteBank"	)
	
	// Create the animation:
	
	m_sprite = new SpriteAnimation( GameCore::GetSingleton()->GetSpriteBank()->GetSprite( GameSpriteBank::SPRITE_HEALTH ) );
	
	// No flipping:
	
	m_sprite->SetFlippingDisabled(true);
	
	// Set these
	
	m_time_till_respawn		= 0;
	m_picked_up_last_frame	= false;
	m_picked_up				= false;
}

//=====================================================================================================================
/// @brief		Destructor.
//=====================================================================================================================

GameHealth::~GameHealth()
{
	delete m_sprite;
}

//=====================================================================================================================
/// @brief		Does an update for the health box
/// @param		time_delta - amount of time between this frame and the last
//=====================================================================================================================

void GameHealth::OnUpdate( float time_delta )
{
	// If there is a change in our status then do a teleport animation:
	
	if ( m_picked_up_last_frame != m_picked_up )
	{
		// Make 
	
		GameTeleportCloud * cloud = new GameTeleportCloud(GetPosition(),true);
		
		// Add to the level
		
		GetManager()->AddObject(cloud);
		
		// Done:
		
		cloud->RemoveReference();
	}

	// Save this:
	
	m_picked_up_last_frame = m_picked_up;
	
	// Server only:
	
	if ( IsServer() )
	{
		// Decrement the time till we can respawn:
		
		m_time_till_respawn -= time_delta;
		
		// See if less than zero:
		
		if ( m_time_till_respawn <= 0 )
		{
			// Clamp at zero
		
			m_time_till_respawn = 0;
			
			// Respawn:
			
			m_picked_up = false;
		}
		
		// Check if any player has picked us up:
		
		CheckPickup();
	}
}

//=====================================================================================================================
/// @brief		Checks for pickups of the health box
/// @pre		This function can only be called on the server
//=====================================================================================================================

void GameHealth::CheckPickup()
{
	// Make sure ok
	
	ENSURE( IsServer() == true , "This function can only be called on the server" )
	
	// Only if we can be picked up:
	
	if ( m_picked_up == true ) return;
	
	// Look for player objects:
	
	std::vector<GameObjectBase*> players; GetManager()->FindByType<GamePlayer>("GamePlayer",players);
	
	// Right: see if any of the players have picked us up:
	
	for ( unsigned i = 0 ; i < players.size() ; ++i )
	{
		// Get this player:
		
		GamePlayer & player = (GamePlayer&)(*players[i]);
		
		// Get the 2d square distance between us:
		
		float dist_2d = Vec2f(player.GetPosition().x,player.GetPosition().z).SqDistanceTo
		(
			Vec2f
			(
				GetPosition().x,
				GetPosition().z
			)
		);
		
		// See if within range:
		
		if ( dist_2d <= PICKUP_RADIUS * PICKUP_RADIUS )
		{
			// Within range: see if the player can pickup the health
			
			if ( player.GetHealth() < GamePlayer::MAX_HEALTH )
			{
				// Can pickup:
				
				m_picked_up = true;
				
				// Reset the time till we can pickup again:
				
				m_time_till_respawn = RESPAWN_TIME;
				
				// Give the player health:
				
				player.SetHealth( player.GetHealth() + 25 );
				
				// Done:
				
				break;
			}
		}
	}
}

//=====================================================================================================================
/// @brief		Network send function. Called on each net object by the GameSession object as required. 
/// @param		packet - packet to send
/// @param		context - context under which the packet is being sent
/// @returns	True to indicate the packet was sent
//=====================================================================================================================

#pragma warning(disable:4100)

bool GameHealth::NetSend( GamePacket & packet , SendContext context )
{
	// This should always be the case:
	
	ENSURE( context == SEND_CONTEXT_REMOTE_TO_CLIENT , "Invalid send context for health box" )

	// Send if we are picked up
	
	packet.WriteFlag(m_picked_up);

	// We sent our update

	return true;
}

#pragma warning(default:4100)

//=====================================================================================================================
/// @brief		Network receive function. Called on each net object by the GameSession object as required. 
/// @param		packet - packet that is being received
/// @param		context - context under which the packet is being received
/// @returns	True if the packet was read sucessfully
//=====================================================================================================================

#pragma warning(disable:4100)

bool GameHealth::NetReceive( GamePacket & packet , ReceiveContext context )
{
	// This should always be the case
	
	ENSURE( context == NetObject::RECV_CONTEXT_REMOTE_TO_CLIENT , "Invalid receive context for health box" )
	
	// Read if we are picked up:
	
	bool picked_up = false;
	
	if ( packet.ReadFlag(picked_up) )
	{
		// Save:
		
		m_picked_up = picked_up;
	
		// Success
		
		return true;
	}
	else
	{
		// Failed to read
		
		return false;
	}
}

#pragma warning(default:4100)

//=====================================================================================================================
/// @brief		Draws the health box
/// @param		c - camera to draw from
/// @pre		GameCore must exist
/// @pre		GameCore must have a sprite renderer
//=====================================================================================================================

void GameHealth::OnDraw( Camera3D * c )
{
	// Make sure ok
	
	ENSURE( GameCore::GetSingleton()						, "GameCore must exist"						)
	ENSURE( GameCore::GetSingleton()->GetSpriteRenderer()	, "GameCore must have a sprite renderer"	)
	
	// Set the position of our sprite:
	
	m_sprite->SetPosition( GetPosition() );
	
	// Only if in scope and not picked up:
	
	if ( m_picked_up == false )
	{
		// Draw:
		
		m_sprite->Draw( c , GameCore::GetSingleton()->GetSpriteRenderer() );
	}
}
