// © 2025 Naked People Team. All Rights Reserved.


#include "InteractionManager.h"
#include "Kismet/GameplayStatics.h"
#include "NakedDesire/Player/NakedDesireCharacter.h"


UInteractionManager::UInteractionManager()
{
	PrimaryComponentTick.bCanEverTick = false;
}

void UInteractionManager::OnTargetEnter(const TScriptInterface<IInteractionTarget>& Target)
{
	InteractionTargets.Add(Target);
}

void UInteractionManager::OnTargetExit(const TScriptInterface<IInteractionTarget>& Target)
{
	InteractionTargets.Remove(Target);
}

TScriptInterface<IInteractionTarget> UInteractionManager::GetNearestInteractionTarget()
{
	const ANakedDesireCharacter* Player = Cast<ANakedDesireCharacter>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));
	TScriptInterface<IInteractionTarget> Target;
	for (const auto& Elem : InteractionTargets)
	{
		const AActor* Actor = Cast<AActor>(Elem.GetObject());
		const AActor* TargetActor = Target ? Cast<AActor>(Target.GetObject()) : nullptr;
		if (!Target || FVector::Distance(Player->GetActorLocation(), Actor->GetActorLocation()) < FVector::Distance(Player->GetActorLocation(), TargetActor->GetActorLocation()))
		{
			Target = Elem;
		}

	}
	
	return Target;
}

