// Project Lab - NHTV Igad

#include "UnrealProject.h"
#include "TrailTrigger.h"
#include "Networkcharacter.h"
#include "TrailActor.h"
#include "Effect.h"
#include "EffectFunctionLibrary.h"

ATrailTrigger::ATrailTrigger()
{
}

void ATrailTrigger::BeginPlay()
{
	Super::BeginPlay();
	if (Role == ROLE_Authority)
	{
		if (character == NULL)
		{
			FERROR("m_character is NULL");
			Destroy();
			return;
		}
		m_lastPos = character->GetActorLocation();
		SpawnTrail(FVector(0, 0, 0), true);
	}
}

void ATrailTrigger::SpawnTrail(FVector offset, bool first)
{

	m_lastPos += offset;
	UCapsuleComponent* newobject = NewObject<UCapsuleComponent>(this);
	newobject->SetCollisionProfileName(TEXT("Triggers"));
	newobject->SetCapsuleRadius(colliderRadius, false);
	newobject->SetCapsuleHalfHeight(500, false);
	newobject->SetWorldLocation(m_lastPos);
	newobject->OnComponentBeginOverlap.AddDynamic(this, &AAbilityTriggerBase::OnOverlapBegin);
	newobject->OnComponentEndOverlap.AddDynamic(this, &AAbilityTriggerBase::OnOverlapEnd);
	newobject->RegisterComponent();
	if(first)
		RootComponent = newobject;

	FTransform effectTransform;
	effectTransform.SetTranslation(m_lastPos);
	effectTransform.SetRotation(character->GetActorRotation().Quaternion());
	UEffectFunctionLibrary::CreateEffectAt(this, trailEffectClass, effectTransform,0.0f,lifeTime);

	//ATrailActor* newTrailActor = GetWorld()->SpawnActor<ATrailActor>(trailActors);
	//if (newTrailActor == nullptr)
	//	return;6
	//newTrailActor->SetActorLocation(m_lastPos);
	//newTrailActor->SetOwner(this);
	//newTrailActor->DynamicAdd();
}

void ATrailTrigger::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	if (Role != ROLE_Authority || !IsValid(this))
		return; 
	if (colliderSpawnDistance == 0)
	{
		FERROR("colliderSpawnDistance == 0");
		return;
	}
	//m_timer += DeltaTime;
	if ( !character ) return;
	FVector distvec = character->GetActorLocation() - m_lastPos;
	distvec.Z = 0;
	float dist = distvec.Size();
	m_totalTimer += DeltaTime;
	lifeTime -= DeltaTime;
	if (lifeTime < 0)
	{
		Destroy();
		return;
	}
	if (m_totalTimer > totalSpawnTime)
	{
		return;
	}
	while (dist > colliderSpawnDistance)
	{
		UCapsuleComponent* newobject = NewObject<UCapsuleComponent>(this);
		distvec.Normalize();
		dist -= colliderSpawnDistance;

		SpawnTrail(distvec *colliderSpawnDistance);
	}

}