/* 
 * Copyright (c)2009-2025 DemiVision, LLC. All Rights Reserved. The information 
 * herein is the CONFIDENTIAL and PROPRIETARY information of DemiVision, LLC. 
 */

using DXLib.UI;
using DXLib.UI.Card;
using DXLib.UI.Container;

using DXLib.Utils;
using Label = MR.Gestures.Label;

namespace iStatVball3;

/*
 * Top-level UI container that manages all DXPage instances for main UI shell list mode. Pages are saved in a stack to
 * support forward/backward navigation.
 */
public class PageStack : DXContent
{
	/* Properties */
	public int Count => pages.Count;
	public DXCardPage CurrentPage => (Count == 0) ? null : pages[ Count - 1 ];

	// Determines if navigation has reached Season Home or beyond
	public bool IsHome => Count > 3;

	/* Fields */
	private readonly List<DXCardPage> pages;

	/* Methods */
	public PageStack()
	{
		BackgroundColor = DXColors.Dark1;

		HorizontalOptions = LayoutOptions.Fill;
		VerticalOptions = LayoutOptions.Fill;

		// Underlying data structure
		pages = [];
	}

	// (Re)displays current page
	public void Refresh()
	{
		ShowPage( CurrentPage );
	}

	// Removes any pages currently on stack
	public void Clear()
	{
		pages.Clear();

		Shell.Instance.PathBar.ClearAll();
	}

	// Pushes new page onto stack, with name of parent page, optionally without display
	public void Push( DXCardPage page, string parent, bool display = true )
	{
		// Save
		pages.Add( page );

		// Display
		if ( display )
		{
			ShowPage( page );
		}

		// Add item to path bar
		PathBarItem item = new()
		{
			ActiveText = page.Title,
			InactiveText = parent
		};

		Shell.Instance.PathBar.Push( item );
	}

	// Removes current page from top of stack, optionally without display
	public void Pop( bool display = true )
	{
		// Can't pop only page
		if ( Count > 1 )
		{
			// Delete
			pages.Remove( CurrentPage );

			// Optionally update UI
			if ( display )
			{
				Refresh();

				Shell.Instance.PathBar.Pop();
			}
		}
	}

	// Displays specified page in UI
	private void ShowPage( DXCardPage page )
	{
		page.LoadCards();

		AppBar appBar = Shell.Instance.AppBar;

		// Update AppBar
		appBar.HasBackButton = (Count > 1);
		appBar.Title = page.Title;
		
		appBar.ResetBack();

		// Must re-layout here
		UpdateLayout();

		Content = page;
	}

	/* Layout */

	// Device/orientation specific layout
	public override void UpdateLayout( LayoutType type )
	{
		DXCardPage page = CurrentPage;

		// Update child page
		page?.UpdateLayout( type );
	}
}

//
