/*
	Trig Wars.
	Copyright (c) 2008, 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 is a base class for all enemies that can fire at the player. Derived classes must initialise
///				all the fields in this class to get the desired attacking behaviour and capabilities.
//=====================================================================================================================

#include "Precompiled.h"
#include "GameObjects\AttackingEnemy.h"
#include "Game\EnemyBulletManager.h"
#include "Game\GameCore.h"

using namespace Game;

//=====================================================================================================================
/// @brief		Updates time to fire etc.
/// @param		time_delta - time since the last frame
/// @remarks	This automatically calls AIControlled::OnUpdate() after it is done
/// @pre		The derived class should have initialised all settings in AttackingEnemy
//=====================================================================================================================

void AttackingEnemy::OnUpdate( float time_delta )
{
	// Make sure ok:

	ENSURE( Float::IsValid(m_fire_interval_min)		, "The derived class should have initialised all settings in AttackingEnemy" )
	ENSURE( Float::IsValid(m_fire_view_cone_angle)	, "The derived class should have initialised all settings in AttackingEnemy" )
	ENSURE( Float::IsValid(m_fire_chance)			, "The derived class should have initialised all settings in AttackingEnemy" )
	ENSURE( Float::IsValid(m_fire_inaccuracy_max)	, "The derived class should have initialised all settings in AttackingEnemy" )

	// Decrement the amount of time till we can fire again:
	
	m_time_till_fire -= time_delta; 
	
	// If less than zero then clamp:
	
	if ( m_time_till_fire < 0 ) m_time_till_fire = 0;
	
	// Do base clas update:
	
	AIControlled::OnUpdate(time_delta);
}

//=====================================================================================================================
/// @brief		Does firing if possible
/// @pre		The derived class should have initialised all settings in AttackingEnemy
/// @pre		The player should be in the game
/// @pre		The game should exist
/// @pre		Fire chance should be between 0 and 1
/// @pre		Fire inaccuracy should not be less than zero
/// @pre		View cone angle for firing should be > 0
/// @pre		Fire interval should be > 0
/// @pre		This object must have a bullet manager in its AI manager
//=====================================================================================================================

void AttackingEnemy::DoFiring()
{
	// Make sure ok:

	ENSURE( Float::IsValid(m_fire_interval_min)			, "The derived class should have initialised all settings in AttackingEnemy"	)
	ENSURE( Float::IsValid(m_fire_view_cone_angle)		, "The derived class should have initialised all settings in AttackingEnemy"	)
	ENSURE( Float::IsValid(m_fire_chance)				, "The derived class should have initialised all settings in AttackingEnemy"	)
	ENSURE( Float::IsValid(m_fire_inaccuracy_max)		, "The derived class should have initialised all settings in AttackingEnemy"	)
	ENSURE( m_fire_chance >= 0 && m_fire_chance <= 1	, "Fire chance should be between 0 and 1"										)
	ENSURE( m_fire_inaccuracy_max >= 0					, "Fire inaccuracy should not be less than zero"								)	
	ENSURE( m_fire_view_cone_angle > 0					, "View cone angle for firing should be > 0"									)
	ENSURE( m_fire_interval_min > 0						, "Fire interval should be > 0"													)	
	ENSURE( GetAIManager().GetBulletManager()			, "This object must have a bullet manager in its AI manager"					)
	
	// In debug mode do no firing if the game is 
	
	#ifdef USE_DEBUG_CONSOLE
	
		if ( GameCore * game = GameCore::GetSingleton() )
		{
			if ( game->NoTargetEnabled() ) return;
		}
	
	#endif
	
	// See if we can fire:
	
	if ( m_time_till_fire <= 0 )
	{
		// Can fire: get the player
		
		PlayerShip * player = GetAIManager().GetPlayerShip();
		
		// Make sure alright:
		
		ENSURE( player , "The player should be in the game" )
		
		// Get the RNG from the game
		
		Random & random = GameCore::GetSingleton()->GetRandom();
		
		// These are the angles of the two direction vectors in our view cone		
		
		float a1;
		float a2;
		
		{
			// Figure out the angles of both view cone vectors
		
			float h = m_fire_view_cone_angle * 0.5f;
			
			a1 = GetAngle() - h;
			a2 = GetAngle() + h;
		}
		
		// Construct the two direction vectors of our view cone:
		
		Vec2f d1 = Vec2f( Float::Cos(a1) , Float::Sin(a1) );
		Vec2f d2 = Vec2f( Float::Cos(a2) , Float::Sin(a2) );
		
		// Get the perpendiculars or normals to the view cone vectors:
		
		Vec2f n1 =  -d1.Perpendicular();
		Vec2f n2 =   d2.Perpendicular();
		
		// Now get the player's position relative to these vectors:
		
		Vec2f r = player->GetPosition() - GetPosition();
		
		// See if the player is in our view cone:
		
		if ( n1.Dot(r) >= 0 && n2.Dot(r) >= 0 )
		{		
			// In our view cone.. see if we can fire:
			
			if ( random.NextFloat() < m_fire_chance )
			{
				// Can fire: get the angle to the player
				
				float angle_to_player = r.GetAngle();
				
				// Pick an amount to vary this angle by:
				
				float inaccuracy = random.NextFloat() * m_fire_inaccuracy_max;
				
				// Decide whether to make it positive or negative:
				
				if ( random.NextBool() ) inaccuracy = -inaccuracy;
				
				// This is the angle we will fire at:
				
				float fire_angle = angle_to_player + inaccuracy;
				
				// Get our bullet manager:
				
				EnemyBulletManager * b_mgr = GetAIManager().GetBulletManager();
				
				// Fire a bullet!!
				
				b_mgr->FireBullet( GetPosition() , fire_angle , GetLinearVelocity().Length() );
			}
		}
	}
}
