// Multiplayer By Caleb


#include "Crunch/Public/Player/CPlayerController.h"

#include "Blueprint/UserWidget.h"
#include "Character/CPlayerCharacter.h"
#include "Net/UnrealNetwork.h"
#include "Widgets/GameplayWidget.h"

void ACPlayerController::GetLifetimeReplicatedProps(TArray<class FLifetimeProperty>& OutLifetimeProps) const
{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);
	DOREPLIFETIME(ACPlayerController, TeamId);
}

void ACPlayerController::OnPossess(APawn* InPawn)
{
	Super::OnPossess(InPawn);
	if (CPlayerCharacter = Cast<ACPlayerCharacter>(InPawn); IsValid(CPlayerCharacter))
	{
		CPlayerCharacter->ServerSideInit();
		CPlayerCharacter->SetGenericTeamId(TeamId);
	}
}

void ACPlayerController::AcknowledgePossession(APawn* P)
{
	Super::AcknowledgePossession(P);
	if (CPlayerCharacter = Cast<ACPlayerCharacter>(P); IsValid(CPlayerCharacter))
	{
		CPlayerCharacter->ClientSideInit();
		SpawnGameplayWidget();
	}
}

FGenericTeamId ACPlayerController::GetGenericTeamId() const
{
	return TeamId;
}

void ACPlayerController::SetGenericTeamId(const FGenericTeamId& NewTeamID)
{
	TeamId = NewTeamID;
}

void ACPlayerController::SpawnGameplayWidget()
{
	if (!IsLocalPlayerController()) return;
	GameplayWidget = CreateWidget<UGameplayWidget>(this, GameplayWidgetClass);
	if (GameplayWidget) GameplayWidget->AddToViewport();
}
