// Fill out your copyright notice in the Description page of Project Settings.


#include "BTTask_FindPlayerLocation.h"

#include "NavigationSystem.h"
#include "BehaviorTree/BlackboardComponent.h"
#include "GameFramework/Character.h"

UBTTask_FindPlayerLocation::UBTTask_FindPlayerLocation(FObjectInitializer const& ObjectInitializer)
{
	NodeName = TEXT("Find Player Location");
}

EBTNodeResult::Type UBTTask_FindPlayerLocation::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
	if (const ACharacter* const Player = Cast<ACharacter>(GetWorld()->GetFirstPlayerController()->GetPawn()))
	{
		if (UBlackboardComponent* const Blackboard = OwnerComp.GetBlackboardComponent())
		{
			if (SearchRandom)
			{
				FVector const Origin = Player->GetActorLocation();
				const UNavigationSystemV1* const NavSystem = UNavigationSystemV1::GetCurrent(GetWorld());
				if (FNavLocation RandomLocation; NavSystem->GetRandomPointInNavigableRadius(Origin, SearchRadius, RandomLocation))
				{
					Blackboard->SetValueAsVector(GetSelectedBlackboardKey(), RandomLocation.Location);
				}
			}
			else
			{
				Blackboard->SetValueAsVector(GetSelectedBlackboardKey(), Player->GetActorLocation());
			}
			FinishLatentTask(OwnerComp, EBTNodeResult::Succeeded);
			return EBTNodeResult::Succeeded;
		}
	}
	return EBTNodeResult::Failed;
}
