// Multiplayer By Caleb


#include "GAS/CAbilitySystemComponent.h"

#include "GAS/CAttributeSet.h"



UCAbilitySystemComponent::UCAbilitySystemComponent()
{
	GetGameplayAttributeValueChangeDelegate(UCAttributeSet::GetHealthAttribute())
		.AddUObject(this, &UCAbilitySystemComponent::HealthUpdated);
}

void UCAbilitySystemComponent::ApplyInitialEffects()
{
	if (!GetOwner() || !GetOwner()->HasAuthority()) return;

	for (const auto& EffectClass : InitialEffects)
	{
		/**
		 * this will work as well
		 * const auto Effect{EffectClass->GetDefaultObject<UGameplayEffect>()};
		 * ApplyGameplayEffectToSelf(Effect, 0.f, MakeEffectContext());
		**/
		AuthApplyGameplayEffect(EffectClass);
	}
}

void UCAbilitySystemComponent::GiveInitialAbilities()
{
	if (!GetOwner() || !GetOwner()->HasAuthority()) return;

	for (const auto& AbilityPairClass : Abilities)
	{
		GiveAbility(FGameplayAbilitySpec(
			AbilityPairClass.Value,
			0,
			static_cast<int32>(AbilityPairClass.Key),
			nullptr
		));
	}
	for (const auto& AbilityPairClass : BasicAbilities)
	{
		GiveAbility(FGameplayAbilitySpec(
			AbilityPairClass.Value,
			1,
			static_cast<int32>(AbilityPairClass.Key),
			nullptr
		));
	}
}

void UCAbilitySystemComponent::HealthUpdated(const FOnAttributeChangeData& ChangeData)
{
	// if (!GetOwner() && !GetOwner()->HasAuthority()) return;
	if (ChangeData.NewValue <= 0 &&  DeathEffectClass)
	{
		AuthApplyGameplayEffect(DeathEffectClass);
	}
}

void UCAbilitySystemComponent::ApplyFullStatEffect()
{
	if (!IsValid(FullStatEffectClass)) return;
	AuthApplyGameplayEffect(FullStatEffectClass);
}

void UCAbilitySystemComponent::AuthApplyGameplayEffect(const TSubclassOf<UGameplayEffect> EffectClass, const int Level)
{
	if (!GetOwner() || !GetOwner()->HasAuthority()) return;
	
	const auto FullStatEffectSpec { MakeOutgoingSpec(EffectClass, Level, MakeEffectContext())};
	ApplyGameplayEffectSpecToSelf(*FullStatEffectSpec.Data.Get());
}
