// © 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"
#include "Kismet/GameplayStatics.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();
}

bool USaveSubsystem::DoesSaveExist() const
{
	return UGameplayStatics::DoesSaveGameExist(ActiveSlotName, SLOT_PLAYER);
}

void USaveSubsystem::StartNewGame()
{
	UGameplayStatics::DeleteGameInSlot(ActiveSlotName, SLOT_PLAYER);

	CurrentSave = UGlobalSaveGameData::CreateNewSaveGame();
	PopulateStartingData(CurrentSave);
	UGlobalSaveGameData::SaveGame(CurrentSave, ActiveSlotName);
}

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 (const UItemDefinition* Definition : GameInstance->StartingSaveData->EquippedItems)
	{
		if (!Definition)
			continue;

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

		Save->AddEquippedItem(Instance);
	}
	
	for (const UItemDefinition* Definition : GameInstance->StartingSaveData->WardrobeItems)
	{
		if (!Definition)
			continue;

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