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

using DXLib.UI.Control.List;
using DXLib.Utils;

namespace iStatVball3;

/*
 * Displays a list of players in a popup menu. Used to select a player for a lineup, substitution, etc.
 */
public class LineupMenu : DXListMenu
{
	/* Events */
	public Action<Player,bool> PlayerSelected { get; set; }
	public Action<LineupEntry> EntrySelected { get; set; }

	/* Properties */
	public string Header { set => menuView.Header = value; }
	public bool HasClear { set => menuView.HasClear = value; }

	public Color MenuColor { set => menuView.Color = value; }

	/* Fields */
	private readonly LineupMenuView menuView;

	// State control
	private bool selectionMade;

	/* Methods */
	public LineupMenu( int rowCount, bool hasFooter, bool rosterMode = true )
	{
		bool tablet = DXDevice.IsTablet;

		IsModal = false;
		Padding = 0;

		// Create underlying view
		menuView = new LineupMenuView
		{
			Embedded = false,
			HasTallRows = tablet,

			PlayerSelected = OnPlayerSelected,
			EntrySelected = OnEntrySelected
		};

		menuView.Init( rowCount, hasFooter, rosterMode );

		SetContent( menuView );

		// Width constant, height dynamic
		ViewWidth = tablet ? 225 : 175;
		ViewHeight = menuView.GetHeight();
	}

	// Passthrough to underlying view
	public void SetPlayers( IList<Player> players, IList<LineupMenuRow.RowState> states = null )
	{
		menuView.SetPlayers( players, states );
	}

	// Populates menu with list of lineup entries (Legacy libero swap)
	public void SetEntries( IList<LineupEntry> entries )
	{
		menuView.SetEntries( entries );
	}

	// Reduces emphasis for subset of players (typically those already in lineup)
	public void SetReduced( List<Player> players )
	{
		menuView.SetReduced( players );
	}

	// Visually disables subset of players
	public void SetDisabled( List<Player> players )
	{
		menuView.SetDisabled( players );
	}

	// Overrides superclass to reset selection state
	public override void ShowFromView( View view, double adjustX = 0, double adjustY = 0, bool forceLeft = false )
	{
		selectionMade = false;

		base.ShowFromView( view, adjustX, adjustY );
	}

	/* Event Callbacks */

	// Calls back registered listener when menu row selected
	private void OnPlayerSelected( Player player, bool cancel )
	{
		PlayerSelected?.Invoke( player, cancel );

		Dismiss();
	}

	// Calls back registered listener when menu row selected
	private void OnEntrySelected( LineupEntry entry )
	{
		if ( entry != null )
		{
			EntrySelected?.Invoke( entry );

			selectionMade = true;
		}

		Dismiss();
	}

	// User dismissed menu without selection
	protected override void OnClosed( object sender, EventArgs args )
	{
		if ( !selectionMade )
		{
			Cancelled?.Invoke();
		}
	}
}

//
