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


#include "BTTask_FindPathPoint.h"

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

UBTTask_FindPathPoint::UBTTask_FindPathPoint(FObjectInitializer const& ObjectInitializer)
{
	NodeName = TEXT("Find Path Point");
}

EBTNodeResult::Type UBTTask_FindPathPoint::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
	if (const AAI_EnemyController* const AIEnemyController = Cast<AAI_EnemyController>(OwnerComp.GetAIOwner()))
	{
		if (UBlackboardComponent* const BlackboardComponent = OwnerComp.GetBlackboardComponent())
		{
			int const Index = BlackboardComponent->GetValueAsInt(GetSelectedBlackboardKey());
			if (const AEnemyCharacter* const EnemyCharacter = Cast<AEnemyCharacter>(AIEnemyController->GetPawn()))
			{
				FVector const RelativePatrolPoint = EnemyCharacter->GetPatrolPath()->GetPatrolPoint(Index);
				FVector const GlobalPointLocation = EnemyCharacter->GetPatrolPath()->GetActorTransform().TransformPosition(RelativePatrolPoint);
				BlackboardComponent->SetValueAsVector(PatrolPathVectorKey.SelectedKeyName, GlobalPointLocation);

				FinishLatentTask(OwnerComp, EBTNodeResult::Succeeded);
				return EBTNodeResult::Succeeded;
			}
		}
	}
	return EBTNodeResult::Failed;
}
