// Copyright Epic Games, Inc. All Rights Reserved.

#include "AgrarianGameGameMode.h"
#include "AgrarianGameCharacter.h"
#include "AgrarianDebugHUD.h"
#include "AgrarianGameState.h"
#include "AgrarianPersistenceSubsystem.h"

AAgrarianGameGameMode::AAgrarianGameGameMode()
{
	GameStateClass = AAgrarianGameState::StaticClass();
	HUDClass = AAgrarianDebugHUD::StaticClass();
}

void AAgrarianGameGameMode::RestartPlayer(AController* NewPlayer)
{
	Super::RestartPlayer(NewPlayer);

	AAgrarianGameCharacter* AgrarianCharacter = NewPlayer ? Cast<AAgrarianGameCharacter>(NewPlayer->GetPawn()) : nullptr;
	UAgrarianPersistenceSubsystem* Persistence = GetGameInstance() ? GetGameInstance()->GetSubsystem<UAgrarianPersistenceSubsystem>() : nullptr;
	if (AgrarianCharacter && Persistence && Persistence->RestorePlayerSnapshot(AgrarianCharacter))
	{
		UE_LOG(LogTemp, Log, TEXT("Agrarian restored reconnect snapshot for %s."), *AgrarianCharacter->GetName());
	}
}

void AAgrarianGameGameMode::Logout(AController* Exiting)
{
	AAgrarianGameCharacter* AgrarianCharacter = Exiting ? Cast<AAgrarianGameCharacter>(Exiting->GetPawn()) : nullptr;
	UAgrarianPersistenceSubsystem* Persistence = GetGameInstance() ? GetGameInstance()->GetSubsystem<UAgrarianPersistenceSubsystem>() : nullptr;
	if (AgrarianCharacter && Persistence)
	{
		Persistence->SavePlayerSnapshot(AgrarianCharacter);
	}

	Super::Logout(Exiting);
}
