// Multipalyer By Caleb


#include "Crunch/Public/Game/CGameMode.h"

#include "EngineUtils.h"
#include "GameFramework/PlayerStart.h"

APlayerController* ACGameMode::SpawnPlayerController(ENetRole InRemoteRole, const FString& Options)
{
	const auto NewPlayerController{Super::SpawnPlayerController(InRemoteRole, Options)};
	const auto NewPlayerControllerTeamInterface{Cast<IGenericTeamAgentInterface>(NewPlayerController)};
	const FGenericTeamId TeamId{GetTeamIDForPlayer(NewPlayerController)};
	if (NewPlayerControllerTeamInterface)
	{
		NewPlayerControllerTeamInterface->SetGenericTeamId(TeamId);
	}
	NewPlayerController->StartSpot = FindNextStartSpotForTeam(TeamId);
	
	return NewPlayerController;
}

FGenericTeamId ACGameMode::GetTeamIDForPlayer(const APlayerController* PlayerController) const
{
	static int PlayerCount{0};
	++PlayerCount;
	return FGenericTeamId(PlayerCount % 2);
}

AActor* ACGameMode::FindNextStartSpotForTeam(const FGenericTeamId& TeamId) const
{
	const auto StartSpotTag{TeamStartSpotTagMap.Find(TeamId)};
	if (!StartSpotTag)
	{
		return nullptr;
	}
	auto World{GetWorld()};
	for (TActorIterator<APlayerStart> It(World); It; ++It)
	{
		if (It->PlayerStartTag == *StartSpotTag)
		{
			It->PlayerStartTag = FName("Taken");
			return *It;
		}
	}
	return nullptr;
}
