// Project Lab - NHTV Igad

#include "UnrealProject.h"

#include "NPCBase.h"
#include "NetworkPlayer.h"
#include "BossBarageBunny.h"


ABossBarageBunny::ABossBarageBunny()
{
	PrimaryActorTick.bCanEverTick = true;

	bReplicates = true;
	bReplicateMovement = true;

	boss = nullptr;

	BeamEmitter = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("Visual"));
	BeamEmitter->AttachTo(RootComponent);

	m_lifeTime = 1;
}

void ABossBarageBunny::BeginPlay()
{
	Super::BeginPlay();
	
	SpawnDefaultController();
}

void ABossBarageBunny::Tick( float DeltaTime )
{
	Super::Tick( DeltaTime );

	// Update the line material
	if (IsValid(boss))
	{
		BeamEmitter->SetBeamSourcePoint(0, GetActorLocation(), 0);
		BeamEmitter->SetBeamTargetPoint(0, boss->GetActorLocation(), 0);
	}
	else
	{
		BeamEmitter->SetActive(false);
		GetCharacterMovement()->MaxWalkSpeed = 0;
	}

	// Server only
	if (Role != ROLE_Authority)
		return;

	m_lifeTime -= DeltaTime;
	if (m_lifeTime <= 0)
	{
		Destroy();
		return;
	}

	// Boss destroyed?
	if (!IsValid(boss))
		return;

	UNavigationSystem* const nav = UNavigationSystem::GetCurrent(GetWorld());
	if (!IsValid(nav)) return;

	AController* const controller = GetController();
	if (!IsValid(controller))
	{
		JERROR("BossBarageBase has no controller");
		return;
	}

	ANPCBase* const asNPC = Cast<ANPCBase>(boss);
	if (!IsValid(asNPC) || !IsValid(asNPC->target))
		return;

	nav->SimpleMoveToLocation(controller, asNPC->target->GetActorLocation());
}


void ABossBarageBunny::Setup(AActor* boss, float lifeTime)
{
	this->boss = boss;
	m_lifeTime = lifeTime;
}

void ABossBarageBunny::ClearBoss()
{
	this->boss = nullptr;
}

void ABossBarageBunny::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	DOREPLIFETIME(ABossBarageBunny, boss);
}
