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


#include "EnemyCharacter.h"

#include "AIControlHub.h"
#include "AIController.h"
#include "BehaviorTree/BlackboardComponent.h"


class UAISense_Sight;
// Sets default values
AEnemyCharacter::AEnemyCharacter()
{
	// Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;
}

// Called when the game starts or when spawned
void AEnemyCharacter::BeginPlay()
{
	Super::BeginPlay();
	CharacterName = "Enemy";
}

void AEnemyCharacter::OnDeath()
{
	Super::OnDeath();
	DelegatedControlHub->AlertLevelEvent.Remove(AlertLevelDelegateHandle);
	DelegatedControlHub->HuntPlayerEvent.Remove(HuntPlayerDelegateHandle);
	AlertLevelDelegateHandle.Reset();
	HuntPlayerDelegateHandle.Reset();
	DelegatedControlHub->RemoveEnemyActor(this);
}

// Called every frame
void AEnemyCharacter::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
}

void AEnemyCharacter::SubscribeToGroupAIEvents(AAIControlHub* ControlHub)
{
	DelegatedControlHub = ControlHub;
	AlertLevelDelegateHandle = ControlHub->AlertLevelEvent.AddUObject(this, &AEnemyCharacter::SetAlertLevel);
	HuntPlayerDelegateHandle = ControlHub->HuntPlayerEvent.AddUObject(this, &AEnemyCharacter::HuntPlayer);
}

void AEnemyCharacter::SetAlertLevel(const int NewAlertLevel) const
{
	if (!IsValid(this)) return;
	if (!IsValid(GetController())) return;
	Cast<AAIController>(GetController())->GetBlackboardComponent()->SetValueAsInt("AlertLevel", NewAlertLevel);
}

void AEnemyCharacter::SetLocalAlertLevel(int NewAlertLevel) const
{
	if (!IsValid(DelegatedControlHub)) return;
	DelegatedControlHub->SetAlertLevel(NewAlertLevel);
}

void AEnemyCharacter::EquipWeapon_Implementation()
{
}

void AEnemyCharacter::DeEquipWeapon_Implementation()
{
}

void AEnemyCharacter::SetFiring_Implementation(bool IsFiring)
{
}

void AEnemyCharacter::HuntPlayer(FVector PlayerLastKnownLocation)
{
	if (!IsValid(this)) return;
	if (!IsValid(GetController())) return;
	SetAlertLevel(2);
	EquipWeapon();
	Cast<AAIController>(GetController())->GetBlackboardComponent()->SetValueAsVector("LastKnownLocation", PlayerLastKnownLocation);
}
