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


#include "BTTask_AttackPlayer.h"

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

UBTTask_AttackPlayer::UBTTask_AttackPlayer(FObjectInitializer const& ObjectInitializer)
{
	NodeName = TEXT("Attack Player");
}

EBTNodeResult::Type UBTTask_AttackPlayer::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
	if (const AAI_EnemyController* const AIController = Cast<AAI_EnemyController>(OwnerComp.GetAIOwner()))
	{
		if (const UBlackboardComponent* const Blackboard = OwnerComp.GetBlackboardComponent())
		{
			FVector const Origin = AIController->GetPawn()->GetActorLocation();
			FVector const Start = Origin + FVector(0.f, 0.f, 30.f);
			FVector const PlayerLocation = Blackboard->GetValueAsVector("TargetLocation");
			DrawDebugLine(GetWorld(), Start, PlayerLocation, FColor::Black, false, 1.f, 0, 1.f);

			FCollisionQueryParams QueryParams;
			QueryParams.AddIgnoredActor(AIController->GetPawn());
			if (FHitResult HitResult; GetWorld()->LineTraceSingleByChannel(HitResult, Start, PlayerLocation, ECC_Pawn, QueryParams))
			{
				if (IsValid(HitResult.GetActor()))
				{
					if (HitResult.GetActor()->ActorHasTag("Player"))
					{
						Cast<AEndlessVendettaCharacter>(HitResult.GetActor())->TakeDamage(5.0f, FPointDamageEvent(), AIController->GetInstigatorController(), AIController->GetPawn());
					}
				}
			}
			if (AEnemyCharacter* const EnemyCharacter = Cast<AEnemyCharacter>(AIController->GetPawn()))
			{
				EnemyCharacter->SetFiring(true);

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