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


#include "BTTask_IncrementPathIndex.h"

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

UBTTask_IncrementPathIndex::UBTTask_IncrementPathIndex(FObjectInitializer const& ObjectInitializer)
{
	NodeName = TEXT("Increment Path Index");
}

EBTNodeResult::Type UBTTask_IncrementPathIndex::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
	if (AAI_EnemyController* const EnemyController = Cast<AAI_EnemyController>(OwnerComp.GetOwner()))
	{
		if (AEnemyCharacter* const EnemyCharacter = Cast<AEnemyCharacter>(EnemyController->GetPawn()))
		{
			if (UBlackboardComponent* const BlackboardComponent = OwnerComp.GetBlackboardComponent())
			{
				int const NumberOfPoints = EnemyCharacter->GetPatrolPath()->Num();
				int const MinIndex = 0;
				int const MaxIndex = NumberOfPoints - 1;
				int CurrentIndex = BlackboardComponent->GetValueAsInt(GetSelectedBlackboardKey());

				if (bBiDirectional)
				{
					if (CurrentIndex >= MaxIndex && DirectionType == Forward)
					{
						DirectionType = Backward;
					}
					else if (CurrentIndex == MinIndex && DirectionType == Backward)
					{
						DirectionType = Forward;
					}
				}
				BlackboardComponent->SetValueAsInt(GetSelectedBlackboardKey(), (DirectionType == Forward ? ++CurrentIndex : --CurrentIndex) % NumberOfPoints);

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