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

#include "AgrarianGameGameMode.h"
#include "AgrarianGameCharacter.h"
#include "AgrarianDebugHUD.h"
#include "AgrarianCampfire.h"
#include "AgrarianGameState.h"
#include "AgrarianPersistenceSubsystem.h"
#include "AgrarianShelterActor.h"
#include "TimerManager.h"

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

void AAgrarianGameGameMode::BeginPlay()
{
	Super::BeginPlay();

	if (HasAuthority())
	{
		LoadWorldOnServerStart();
	}

	if (HasAuthority() && ServerAutoSaveIntervalSeconds > 0.0f)
	{
		GetWorldTimerManager().SetTimer(
			ServerAutoSaveTimerHandle,
			this,
			&AAgrarianGameGameMode::RunServerAutoSave,
			ServerAutoSaveIntervalSeconds,
			true,
			ServerAutoSaveIntervalSeconds);
	}
}

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);
}

void AAgrarianGameGameMode::RegisterPersistentActorClasses(UAgrarianPersistenceSubsystem* Persistence) const
{
	if (!Persistence)
	{
		return;
	}

	Persistence->RegisterWorldActorClass(TEXT("primitive_shelter"), AAgrarianShelterActor::StaticClass());
	Persistence->RegisterWorldActorClass(TEXT("campfire"), AAgrarianCampfire::StaticClass());
}

void AAgrarianGameGameMode::LoadWorldOnServerStart()
{
	if (!HasAuthority() || !bLoadWorldOnServerStart)
	{
		return;
	}

	UAgrarianPersistenceSubsystem* Persistence = GetGameInstance() ? GetGameInstance()->GetSubsystem<UAgrarianPersistenceSubsystem>() : nullptr;
	if (!Persistence)
	{
		UE_LOG(LogTemp, Warning, TEXT("Agrarian startup load skipped: persistence subsystem unavailable."));
		return;
	}

	RegisterPersistentActorClasses(Persistence);
	if (!Persistence->DoesSaveExist())
	{
		UE_LOG(LogTemp, Log, TEXT("Agrarian startup load skipped: no save exists."));
		return;
	}

	int32 RestoredPlayerCount = 0;
	int32 RestoredActorCount = 0;
	constexpr bool bClearExistingActors = false;
	const bool bLoaded = Persistence->LoadCurrentWorld(RestoredPlayerCount, RestoredActorCount, bClearExistingActors);
	UE_LOG(
		LogTemp,
		Log,
		TEXT("Agrarian startup load %s. Restored players: %d. Restored actors: %d."),
		bLoaded ? TEXT("completed") : TEXT("completed with world-state warning"),
		RestoredPlayerCount,
		RestoredActorCount);
}

void AAgrarianGameGameMode::RunServerAutoSave()
{
	if (!HasAuthority())
	{
		return;
	}

	UAgrarianPersistenceSubsystem* Persistence = GetGameInstance() ? GetGameInstance()->GetSubsystem<UAgrarianPersistenceSubsystem>() : nullptr;
	if (!Persistence)
	{
		UE_LOG(LogTemp, Warning, TEXT("Agrarian server autosave skipped: persistence subsystem unavailable."));
		return;
	}

	const bool bSaved = Persistence->SaveCurrentWorld();
	UE_LOG(LogTemp, Log, TEXT("Agrarian server autosave %s."), bSaved ? TEXT("completed") : TEXT("failed"));
}
