// Project Lab - NHTV Igad

#include "UnrealProject.h"
#include "CharacterSettings.h"
#include "SkillTreeWidget.h"
#include "UserWidget.h"

#define SAVE_SLOT_NAME TEXT("WIEBERSAVE tm")

static UClass* skillTreeWidgetClass;

UCharacterSettings::UCharacterSettings(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	skillTreeWidgetClass = ConstructorHelpers::FClassFinder<USkillTreeWidget>(TEXT("/Game/Assets/GUI/WEEGEE_SkillTree")).Class;
}

UCharacterSettings* UCharacterSettings::Load()
{
	UCharacterSettings* settings = Cast<UCharacterSettings>(UGameplayStatics::LoadGameFromSlot(SAVE_SLOT_NAME, 0));
	if (!settings)
	{
		settings = Cast<UCharacterSettings>(UGameplayStatics::CreateSaveGameObject(UCharacterSettings::StaticClass()));
	}
	check(settings);

	for (auto& save : settings->characterSaves)
	{
		for (TFieldIterator<UProperty> PropIt(FCharacterCustomization::StaticStruct()); PropIt; ++PropIt)
		{
			UFloatProperty* fProperty = Cast<UFloatProperty>(*PropIt);

			if (IsValid(fProperty))
			{
				float* valPtr = fProperty->GetPropertyValuePtr_InContainer(&save.characterCustomization);
				*valPtr = FMath::Clamp(*valPtr, 0.5f, 1.5f);
			}

		}
	}

	return settings;
}

void UCharacterSettings::Save(UCharacterSettings* settings)
{
	UGameplayStatics::SaveGameToSlot(settings, SAVE_SLOT_NAME, 0);
}

TArray<FCharacterSave> UCharacterSettings::GetValidCharacters() const
{
	UCharacterSettings* settings = Cast<UCharacterSettings>(UGameplayStatics::LoadGameFromSlot(SAVE_SLOT_NAME, 0));
	if (!settings)
	{
		settings = Cast<UCharacterSettings>(UGameplayStatics::CreateSaveGameObject(UCharacterSettings::StaticClass()));
	}
	check(settings);

	TArray<FCharacterSave> result;
	for (FCharacterSave& save : settings->characterSaves)
	{
		if (save.skillTreeState.ValidateSkillTree())
			result.Add(save);
	}
	return result;
}