// Project Lab - NHTV Igad

#include "UnrealProject.h"
#include "MenuScreenBase.h"
#include "PlayerControllerBase.h"
#include "SubMenu.h"
#include "WidgetBlueprintLibrary.h"

UMenuScreenBase::UMenuScreenBase(const FObjectInitializer& init)
	: Super(init)
{
	registerMenuActions = false;
}
void UMenuScreenBase::NativeConstruct()
{
	Super::NativeConstruct();
	APlayerControllerBase* pcb = Cast<APlayerControllerBase>(GetWorld()->GetFirstPlayerController());
	if(registerMenuActions && pcb)
	{
		pcb->AddMenuInputItem(this);
	}
}
void UMenuScreenBase::NativeDestruct()
{
	Super::NativeDestruct();
	APlayerControllerBase* pcb = Cast<APlayerControllerBase>(GetWorld()->GetFirstPlayerController());
	if(registerMenuActions && pcb)
	{
		pcb->RemoveMenuInputItem(this);
	}
}

void UMenuScreenBase::OpenSubMenu(class USubMenu* submenu)
{
	if(m_subMenus.Contains(submenu))
	{
		GWARNING("Submenu already active");
		return;
	}

	if(!submenu)
	{
		GWWARNING(L"Invalid submenu passed to OpenSubMenu");
		return;
	}

	submenu->OnEnter(this);
	if(m_subMenus.Num() > 0)
	{
		m_subMenus.Last()->OnSuspend(submenu, true);
	}
	m_subMenus.Add(submenu);

	UWidgetBlueprintLibrary::SetFocusToGameViewport();
}
void UMenuScreenBase::CloseActiveSubMenu()
{
	if(m_subMenus.Num() > 0)
	{
		CloseSubMenu(m_subMenus.Last());
	}
	else
	{
		GWWARNING("No SubMenus to close");
		return;
	}
}

void UMenuScreenBase::CloseSubMenu(class USubMenu* submenu)
{
	if(!m_subMenus.Contains(submenu))
		return;

	submenu->OnLeave();

	// Restore underlying menus if that was the top-most menu
	if(m_subMenus.Num() > 1)
	{
		bool wasLast = m_subMenus.Last() == submenu;
		m_subMenus.Remove(submenu);
		if(wasLast)
		{
			m_subMenus.Last()->OnRestore(submenu);
		}
	}
	else
	{
		// Remove last menu
		m_subMenus.Remove(submenu);
	}

	UWidgetBlueprintLibrary::SetFocusToGameViewport();
}

TArray<class USubMenu*> UMenuScreenBase::GetSubMenus()
{
	return m_subMenus;
}
class USubMenu* UMenuScreenBase::GetActiveSubMenu()
{
	if(m_subMenus.Num() == 0)
		return nullptr;
	return m_subMenus.Last();
}

void UMenuScreenBase::SetButtonHintBar(class UButtonHintBar* bar)
{
	m_buttonHintBar = bar;
}
class UButtonHintBar* UMenuScreenBase::GetButtonHintBar() const
{
	return m_buttonHintBar;
}

void UMenuScreenBase::NativeOnMenuAction(EMenuActionBinding action)
{
	if(m_subMenus.Num() > 0)
	{
		m_subMenus.Last()->NativeOnMenuAction(action);
	}
	Super::NativeOnMenuAction(action);
}