// © 2025 Naked People Team. All Rights Reserved.


#include "SaveSubsystem.h"

#include "GlobalSaveGameData.h"
#include "ItemSaveRecord.h"
#include "StartingSaveData.h"
#include "NakedDesire/Items/ItemDefinition.h"
#include "NakedDesire/Items/ItemInstance.h"
#include "NakedDesire/Global/NakedDesireGameInstance.h"

void USaveSubsystem::LoadGame(const FString& SlotName)
{
	CurrentSave = UGlobalSaveGameData::LoadGame(SlotName);
}

bool USaveSubsystem::SaveGame(const FString& SlotName) const
{
	return UGlobalSaveGameData::SaveGame(CurrentSave, SlotName);
}

void USaveSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
	Super::Initialize(Collection);

	LoadGame();
}

UGlobalSaveGameData* USaveSubsystem::GetCurrentSave()
{
	if (!CurrentSave)
	{
		CurrentSave = UGlobalSaveGameData::LoadGame(ActiveSlotName);
		if (!CurrentSave)
		{
			CurrentSave = UGlobalSaveGameData::CreateNewSaveGame();
			PopulateStartingData(CurrentSave);
			UGlobalSaveGameData::SaveGame(CurrentSave, ActiveSlotName);
		}
	}

	return CurrentSave;
}

void USaveSubsystem::BP_LoadGame()
{
	LoadGame();
}

void USaveSubsystem::BP_SaveGame()
{
	SaveGame();
}

void USaveSubsystem::PopulateStartingData(UGlobalSaveGameData* Save) const
{
	if (!Save)
		return;

	const UNakedDesireGameInstance* GameInstance = Cast<UNakedDesireGameInstance>(GetGameInstance());
	if (!GameInstance || !GameInstance->StartingSaveData)
		return;

	for (UItemDefinition* Definition : GameInstance->StartingSaveData->StartingItems)
	{
		if (!Definition)
			continue;

		UItemInstance* Instance = Definition->CreateInstance(Save);
		if (!Instance)
			continue;

		Save->AddEquippedItem(Instance);
	}
}
