// Project Lab - NHTV Igad

#include "UnrealProject.h"
#include "SelectButton.h"
#include "DefaultGameInstance.h"
#include "Prefs.h"
#include "GraphicsMenu.h"



void UGraphicsMenu::NativeTick(const FGeometry& MyGeometry, float InDeltaTime)
{
	Super::NativeTick(MyGeometry, InDeltaTime);

	m_Update();
}


void UGraphicsMenu::InitButtons(USelectButton* templateButton, TArray<USelectButton*> settingButtons)
{
	m_templateButton = templateButton;
	m_settingButtons = settingButtons;

	if (!IsValid(m_templateButton) || m_settingButtons.Num() != 6)
	{
		JERROR("InitButton arguments invalid");
		m_templateButton = nullptr;
		return;
	}

	UDefaultGameInstance* instance = Cast<UDefaultGameInstance>(GetGameInstance());
	if (!IsValid(instance))
		return;

	UPrefs* const prefs = instance->GetPrefs();
	int32 fetchPreset = instance->GetScalabilityQuality();
	templateButton->selected = prefs->usingCustomGraphicsSettings ? 0 : fetchPreset + 1;

	m_previousSelection = -5;
	m_Update();
}


void UGraphicsMenu::Apply()
{
	UDefaultGameInstance* instance = Cast<UDefaultGameInstance>(GetGameInstance());
	if (!IsValid(m_templateButton) || !IsValid(instance))
		return;

	const int32 current = m_templateButton->selected;
	if (current > 0)
	{
		// Store the template setting
		instance->SetScalabilityQuality(current - 1);
	}
	else
	{
		// Store the individual sub settings
		instance->SetScalabilityQualityValues(
			m_settingButtons[0]->selected,
			m_settingButtons[1]->selected,
			m_settingButtons[2]->selected,
			m_settingButtons[3]->selected,
			m_settingButtons[4]->selected,
			m_settingButtons[5]->selected);
	}
}

void UGraphicsMenu::m_Update()
{
	UDefaultGameInstance* instance = Cast<UDefaultGameInstance>(GetGameInstance());
	if (!IsValid(m_templateButton) || !IsValid(instance))
		return;

	const int32 current = m_templateButton->selected;
	if (m_previousSelection != current) // Only update when the value has changed
	{
		if (current == 0)
		{
			// Enable the sub setting buttons
			for (int32 i = 0; i < m_settingButtons.Num(); i++)
				m_settingButtons[i]->SetIsEnabled(true);

			// Fetch the stored sub settings from prefs
			TArray<int32> customSettings = instance->GetPrefs()->customGraphicsSettings;
			if (customSettings.Num() <= m_settingButtons.Num())
			{
				for (int32 i = 0; i < customSettings.Num(); i++)
					m_settingButtons[i]->selected = customSettings[i];
			}
		}
		else
		{
			// Disable the subsetting buttons and set them to the template
			for (int32 i = 0; i < m_settingButtons.Num(); i++)
			{
				m_settingButtons[i]->SetIsEnabled(false);
				m_settingButtons[i]->selected = current - 1;
			}
		}
		m_previousSelection = current;
	}
}