// Copyright CodeSpartan, 2022. All rights reserved.

#include "GameModeBaseCpp.h"
#include "GameFramework/PlayerState.h"
#include "PlayerControllerCpp.h"
#include "Net/OnlineEngineInterface.h"
#include "GameFramework/GameSession.h"
#if UE_EDITOR
#include "Editor.h"
#endif

void AGameModeBaseCpp::InitGameState()
{
	Super::InitGameState();

#if UE_EDITOR
	OnEndPieHandle = FEditorDelegates::EndPIE.AddUObject(this, &AGameModeBaseCpp::HandleEndPIE);
#endif
}

AGameModeBaseCpp::~AGameModeBaseCpp()
{
#if UE_EDITOR
	FEditorDelegates::EndPIE.Remove(OnEndPieHandle);
#endif
}

#if UE_EDITOR
void AGameModeBaseCpp::HandleEndPIE(const bool InIsSimulating)
{
	K2_OnEndPIE();
}
#endif

void AGameModeBaseCpp::PreLogin(const FString& Options, const FString& Address, const FUniqueNetIdRepl& UniqueId, FString& ErrorMessage)
{
	// This is the original method. Parts of it have been commented out to allow login from Steam Subsystem to Null Subsystem

	// Login unique id must match server expected unique id type OR No unique id could mean game doesn't use them
	//const bool bUniqueIdCheckOk = (!UniqueId.IsValid() || UOnlineEngineInterface::Get()->IsCompatibleUniqueNetId(UniqueId));
	//if (bUniqueIdCheckOk)
	//{
		ErrorMessage = GameSession->ApproveLogin(Options);
	//}
	//else
	//{
		//ErrorMessage = TEXT("incompatible_unique_net_id");
	//}
	FGameModeEvents::GameModePreLoginEvent.Broadcast(this, UniqueId, ErrorMessage);
}

void AGameModeBaseCpp::RestartPlayerAtPlayerStart(AController* NewPlayer, AActor* StartSpot)
{
	if (NewPlayer == nullptr || NewPlayer->IsPendingKillPending())
	{
		return;
	}
	static_cast<APlayerControllerCpp*>(NewPlayer)->CustomPlayerStart();
}

void AGameModeBaseCpp::ContinuePlayerStart(AController* NewPlayer, APawn* NewPawn, FRotator SpawnRotation)
{
	if (IsValid(NewPawn))
	{
		NewPlayer->SetPawn(NewPawn);
	}
	FinishRestartPlayer(NewPlayer, SpawnRotation);
}

void AGameModeBaseCpp::AbortPlayerStart(AController* NewPlayer)
{
	FailedToRestartPlayer(NewPlayer);
	NewPlayer->Destroy();
}

void AGameModeBaseCpp::KickPlayer(APlayerController* PlayerController)
{
	GameSession->KickPlayer(PlayerController, FText::FromString(TEXT("Kicked")));
}
