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


#include "BTTask_FindRandomLocation.h"

#include "EndlessVendetta/AI/AI_EnemyController.h"
#include "NavigationSystem.h"
#include "BehaviorTree/BlackboardComponent.h"

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

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