
#include "MW4Headers.hpp"

#include "DamageDispatch_SinglePlayer.hpp"
#include "MWDamageObject.hpp"

extern int g_nMR;

using namespace MechWarrior4;

MWObject* GetParentVehicle(MWInternalDamageObject& internal_damage_object)
{ 
	if ((internal_damage_object.parentEntity != 0) &&
		(internal_damage_object.parentEntity->IsDerivedFrom(MWMover::DefaultData) == true))
	{
		MWMover* mwmover = Cast_Object(MWMover*,internal_damage_object.parentEntity);

		return (mwmover->GetParentVehicle());
	}

	return (0);
}

void DamageDispatch_SinglePlayer::InflictCriticalHit(MWInternalDamageObject& internal_damage_object)
{
	if (GetGlobalInvulnerability() == true)
	{
		MWObject* parent = GetParentVehicle(internal_damage_object);

		if ((parent != 0) &&
			(parent->IsPlayerVehicle() == true))
		{
			return;
		}
	}
	
	internal_damage_object._InflictCriticalHit();
}

Scalar DamageDispatch_SinglePlayer::TakeDamage(MWInternalDamageObject& internal_damage_object, Scalar damage_taken, Entity__TakeDamageMessage *message)
{
	if (GetGlobalInvulnerability() == true)
	{
		MWObject* parent = GetParentVehicle(internal_damage_object);

		if ((parent != 0) &&
			(parent->IsPlayerVehicle() == true))
		{
			return (0);
		}
	}

	if ((internal_damage_object.parentEntity != 0) &&
		(internal_damage_object.parentEntity->IsDerivedFrom(MWObject::DefaultData) == true))
	{
		MWObject* mwobject = Cast_Object(MWObject*,internal_damage_object.parentEntity);
		if (mwobject->FriendlyFireDamageMultiplier() != 1)
		{
			Connection *connection = Network::GetInstance()->GetConnection(message->inflictingEntityID.connectionID);
			if (connection != 0)
			{
				Check_Object(connection);

				Entity *entity = Cast_Object(Entity*,connection->FindReplicator(message->inflictingEntityID));

				if ((entity != 0) &&
					(entity->GetAlignment() == mwobject->GetAlignment()))
				{
					damage_taken *= mwobject->FriendlyFireDamageMultiplier();
				}
			}
		}
	}
	
	return (internal_damage_object._TakeDamage(damage_taken,message));
}

void DamageDispatch_SinglePlayer::KillAllContainedSubsystems(MWInternalDamageObject& internal_damage_object)
{
	if (GetGlobalInvulnerability() == true)
	{
		MWObject* parent = GetParentVehicle(internal_damage_object);

		if ((parent != 0) &&
			(parent->IsPlayerVehicle() == true))
		{
			return;
		}
	}
	
	internal_damage_object._KillAllContainedSubsystems();
}
