/*
 * 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.Layout;
using DXLib.UI.Control;
using DXLib.UI.Container;

using DXLib.Utils;

namespace iStatVball3;

/*
 * Implements a popup menu for selecting a Root link to associate two entities (typically Players) for the purposes of
 * analyzing career stats. The menu uses a RootTree for the selection UI.
 */
public class RootSelector
{
	/* Events */
	public Action<RootTreeData> Selected { get; set; }
	public Action Closed { get; set; }

	/* Properties */
	public bool HasChanges { get; private set; }

	/* Fields */
	private readonly DXPopup popup;
	private readonly DXAbsoluteLayout layout;
	private readonly RootTree rootTree;

	/* Methods */
	public RootSelector()
	{
		// Container for padding
		layout = new DXAbsoluteLayout
		{
			BackgroundColor = DXColors.Light4,
			Padding = 15
		};

		// Tree control
		rootTree = new RootTree
		{
			Populated = OnPopulated,
			Selected = OnSelected
		};

		layout.Add( rootTree );
		layout.SetFullBounds( rootTree );

		// Non-modal popup
		popup = new DXPopup( DXString.Get( "root.title" ), layout )
		{
			ViewWidth = 250,
			ViewHeight = 450,

			PopupClosed = OnClosed
		};
	}

	// Post construction initialization
	public async Task Init( Season season )
	{
		DXSpinner.Start();

		// Populate tree
		int count = await rootTree.Init( season );

		// Empty results, notify user
		if ( count == 0 )
		{
			ShowEmpty();
		}
	}

	// Show popup menu
	public void Show( View view )
	{
		HasChanges = false;

		popup.ShowFromView( view );
	}

	// Hide popup menu
	public void Dismiss()
	{
		popup.Dismiss();
	}

	// Reset menu for reuse
	public void Reset()
	{
		HasChanges = false;

		rootTree.SelectedItem = null!;
	}

	// Displays empty result message when no past seasons
	private void ShowEmpty()
	{
		rootTree.IsVisible = false;

		// Label
		DXLabel emptyLbl = new DXLabel
		{
			Resource = "root.empty",
			Margin = new Thickness( 15, 20 ),

			TextColor = DXColors.Dark4,
			Font = DXFonts.RobotoItalic,
			FontSize = 17,

			LineBreakMode = LineBreakMode.WordWrap,
			HAlign = TextAlignment.Center,
			Horizontal = LayoutOptions.Center
		};

		layout.Add( emptyLbl );
		layout.SetFullBounds( emptyLbl );
	}

	/* Event Callbacks */

	// Tree finished loading
	private void OnPopulated()
	{
		DXSpinner.Stop();
	}

	// User selected entity from tree control
	private void OnSelected( RootTreeData root )
	{
		HasChanges = true;

		// Callback registered listener
		Selected?.Invoke( root );
	}

	// User cancelled popup
	private void OnClosed()
	{
		Closed?.Invoke();
	}
}

//
