// Project Lab - NHTV Igad

#include "UnrealProject.h"
#include "DefaultGameInstance.h"
#include "DefaultGameMode.h"
#include "PlayerSpawn.h"
#include "DefaultGameState.h"
#include "DefaultGameInstance.h"
#include "NetworkCharacter.h"

#include "DefaultPlayer.h"
#include "KingOfTheHillGameMode.h"
#include "KOTHBossSpawner.h"
#if PLATFORM_SPECIFIC_WIN == 0
#include "InputManager.hpp"
using namespace Input;
#endif
#include "DefaultPlayerController.h"

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


	RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
	
	// Create a camera boom
	CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
	CameraBoom->AttachTo(RootComponent);
	CameraBoom->bAbsoluteRotation = true;
	CameraBoom->TargetArmLength = 1500.f;
	CameraBoom->RelativeRotation = FRotator(-60.f, 45.f, 0.f);
	CameraBoom->bDoCollisionTest = false;
	CameraBoom->bInheritPitch = false;
	CameraBoom->bInheritYaw = false;
	CameraBoom->bInheritRoll = false;

	// Create a camera
	TopDownCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("TopDownCamera"));
	TopDownCamera->AttachTo(CameraBoom, USpringArmComponent::SocketName);
	TopDownCamera->bUsePawnControlRotation = false;

	// Don't rotate character to camera direction
	bUseControllerRotationPitch = false;
	bUseControllerRotationYaw = false;
	bUseControllerRotationRoll = false;

	
	respawnDelay = 0.25f;
	respawnTimer = 0.0f;
	isRespawning = false;
	bReplicates = true;
	bAlwaysRelevant = true;
	bReplicateMovement = false;
}
void ADefaultPlayer::BeginPlay()
{
	Super::BeginPlay();
	if(Role == ROLE_Authority)
		isRespawning = true;
}

void ADefaultPlayer::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	Super::EndPlay(EndPlayReason);
}
void ADefaultPlayer::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);

	// Spawn the player
	if(Role == ROLE_Authority)
	{
		if(isRespawning)
		{
			respawnTimer -= DeltaSeconds;
			m_OnRep_RespawnTimer();
			bool respawn = true;
			AKingOfTheHillGameMode* gameMode = Cast<AKingOfTheHillGameMode>(GetWorld()->GetAuthGameMode());
			if (gameMode)
			{
				respawn = gameMode->bossSpawner->IsBossAlive();
			}
			if(respawnTimer <= 0.0f &&respawn)
			{
				ADefaultPlayerController* controller = Cast<ADefaultPlayerController>(GetController());
				if(IsValid(controller))
				{
					controller->SpawnCharacterForClient();
					isRespawning = false;
				}
				else
				{
					isRespawning = false;
				}
			}
		}
	}
}

void ADefaultPlayer::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);
	DOREPLIFETIME(ADefaultPlayer, respawnTimer);
	DOREPLIFETIME(ADefaultPlayer, isRespawning);
}

void ADefaultPlayer::OnSpawn()
{
	check(Role == ROLE_Authority);
	respawnTimer = respawnDelay;
	isRespawning = true;
	m_OnRep_RespawnTimer();
}

void ADefaultPlayer::m_OnRep_RespawnTimer()
{
	onRespawnTimerSet.Broadcast(respawnTimer);
}