// Project Lab - NHTV Igad

#include "UnrealProject.h"
#include "AbilityInfo.h"
#include "NetworkCharacter.h"
#include "PreCastAbilityEventGroup.h"





void APreCastAbilityEventGroup::BeginPlay()
{
	check(Role == ROLE_Authority);
	Super::BeginPlay();

	if (!character || character->IsActorBeingDestroyed())
	{
		Destroy();
	}
	else
	{
		// Handle the destruction of the caster
		character->OnDestroyed.AddDynamic(this, &APreCastAbilityEventGroup::m_OnCharacterDestroyed);
	}
}
void APreCastAbilityEventGroup::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	check(Role == ROLE_Authority);
	if (EndPlayReason == EEndPlayReason::Destroyed)
	{
		Super::EndPlay(EndPlayReason);
		StartAbility();
	}
}
void APreCastAbilityEventGroup::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if (IsPendingKill())
		return;
}

void APreCastAbilityEventGroup::m_OnCharacterDestroyed()
{
	Destroy();
}

void APreCastAbilityEventGroup::StartAbility()
{
	character->m_CastAbility_Server(abilityInfo);
	Destroy();
}	


APreCastAbilityEventGroup* APreCastAbilityEventGroup::InitPreCast(UAbilityInfo* info, ANetworkCharacter* character)
{
	UWorld* world = character->GetWorld();
	check(world);

	APreCastAbilityEventGroup* group = world->SpawnActorDeferred<APreCastAbilityEventGroup>(info->precastEvent, FTransform::Identity);

	group->character = character;
	//group->abilityState = character->GetAbilityState(info);
	group->abilityInfo = info;

	UGameplayStatics::FinishSpawningActor(group, FTransform::Identity);
	return group;
}