// Project Lab - NHTV Igad

#include "UnrealProject.h"
#include "KOTHSpawnerBase.h"
#include "NetworkPlayer.h"
#include "KOTHBossSpawner.h"
AKOTHSpawnerBase::AKOTHSpawnerBase(const FObjectInitializer& init)
{
	captureRadius = 500;
	captureTime = 30;
	possesionTime = 1;

	captureParticle = CreateDefaultSubobject<UParticleSystemComponent>("PossessParticle");
	captureParticle->AttachTo(RootComponent);
}

void AKOTHSpawnerBase::BeginPlay()
{
	Super::BeginPlay();

	// Assign team
	m_currentTeam = (int)team;

	beingCaptured = false;
}
void AKOTHSpawnerBase::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	// Run capture polling code on host
	if(Role == ROLE_Authority)
	{
		if(beingCaptured)
		{
			bool capture = false;
			auto nearbyPlayers = GetNearbyPlayers();
			// Check contested condition
		
			if (m_mobCount == 0 && (nearbyPlayers.Num() <= 2))
			{

				if (nearbyPlayers.Num() > 0 && !IsContested(nearbyPlayers[0]->GetTeam()) && (int)team != nearbyPlayers[0]->GetTeam())
				{
					capture = true;

					if (bossSpawner)
					{
						if ((int)bossSpawner->team == nearbyPlayers[0]->GetTeam() || (int)team < 5)
						{
							capture = false;
						}
					}
				}
			}

			if(capture)
			{
				m_possesionTimer += DeltaTime;
				if(m_possesionTimer > possesionTime)
				{
					// Nearby team captures camp
					m_ExeCaptureCamp(nearbyPlayers[0]->GetTeam());
				}
			}
			else
			{
				m_possesionTimer = 0;
			}
		}
	}
}

void AKOTHSpawnerBase::m_ExeCaptureCamp_Implementation(int32 targetTeam)
{
	if(Role == ROLE_Authority)
	{
		SetTeam(targetTeam);
		onCampCaptured.Broadcast(targetTeam);
		m_captureTimer = captureTime;
		m_currentTeam = (int)NPCTeam::Team1;
		beingCaptured = false;
		m_reset = false;
	}

	// Callback
	OnEndCaptureCamp(targetTeam);
	onEndCapture.Broadcast(targetTeam);

	// Deactivate capture particle
	captureParticle->DeactivateSystem();
}

void AKOTHSpawnerBase::m_OnCampCleared()
{
	Super::m_OnCampCleared();

	if(Role == ROLE_Authority)
	{
		beingCaptured = true;
	}

	// Callback
	OnBeginCaptureCamp();
	onBeginCapture.Broadcast();

	// Enable capture particle
	if(captureParticle->Template)
	{
		captureParticle->bAutoDestroy = false;
		captureParticle->ResetParticles();
		captureParticle->ActivateSystem();
	}
}

void AKOTHSpawnerBase::CaptureCamp(int targetTeam)
{
	Super::CaptureCamp(targetTeam);

	m_currentTeam = targetTeam;
	m_possesionTimer = 0;
}

bool AKOTHSpawnerBase::IsContested(int32 targetTeam) const
{
	for(ANetworkCharacter* character : m_nearbyPlayers)
	{
		ANetworkPlayer* player = Cast<ANetworkPlayer>(character);
		if(player && player->GetTeam() != targetTeam && FVector::DistSquared(GetActorLocation(), player->GetActorLocation()) < captureRadius * captureRadius)
			return true;
	}
	return false;
}