using System.Collections.Generic;
using UnityEngine;
namespace Core.UI
{
///
/// Abstract base class of a MainMenu
/// The concrete class should expose serialized fields for the different pages e.g. OptionsMenu
/// The concrete class should expose methods for change pages that use ChangePage() under the hood. e.g. OpenOptionsMenu()
///
public abstract class MainMenu : MonoBehaviour
{
///
/// Currently open MenuPage
///
protected IMainMenuPage m_CurrentPage;
///
/// This stack is to track the pages used to get to specific page - use by the back methods
///
protected Stack m_PageStack = new Stack();
///
/// Change page
///
/// the page to transition to
protected virtual void ChangePage(IMainMenuPage newPage)
{
DeactivateCurrentPage();
ActivateCurrentPage(newPage);
}
///
/// Deactivates the current page is there is one
///
protected void DeactivateCurrentPage()
{
if (m_CurrentPage != null)
{
m_CurrentPage.Hide();
}
}
///
/// Activates the new page, sets it to the current page an adds it to the stack
///
/// the page to be activated
protected void ActivateCurrentPage(IMainMenuPage newPage)
{
//
m_CurrentPage = newPage;
m_CurrentPage.Show();
m_PageStack.Push(m_CurrentPage);
}
///
/// Goes back to a certain page
///
/// Page to go back to
protected void SafeBack(IMainMenuPage backPage)
{
DeactivateCurrentPage();
ActivateCurrentPage(backPage);
}
///
/// Goes back one page if possible
///
public virtual void Back()
{
if (m_PageStack.Count == 0)
{
return;
}
DeactivateCurrentPage();
m_PageStack.Pop();
ActivateCurrentPage(m_PageStack.Pop());
}
///
/// Goes back to a specified page if possible
///
/// Page to go back to
public virtual void Back(IMainMenuPage backPage)
{
int count = m_PageStack.Count;
if (count == 0)
{
SafeBack(backPage);
return;
}
for (int i = count - 1; i >= 0; i--)
{
IMainMenuPage currentPage = m_PageStack.Pop();
if (currentPage == backPage)
{
SafeBack(backPage);
return;
}
}
SafeBack(backPage);
}
}
}