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

using DXLib.UI.Card;
using DXLib.UI.Alert;
using DXLib.UI.Control;

using DXLib.Utils;

namespace iStatVball3;

/*
 * Card page for list of lineups within a parent season.
 */
public class LineupPage : CardPage
{
	/* Methods */
	public LineupPage( Season season ) : base( season )
	{
		Title = DXString.Get( "lineup.plural" );
	}

	/* Abstracts */

	// Displays all lineup cards
	public override void LoadCards()
	{
		Clear();

		// Required for permissions
		User user = Shell.CurrentUser;

		if ( data is Season season )
		{
			// Add card for each lineup
			foreach ( Lineup lineup in season.Lineups )
			{
				LineupCard card = new( season )
				{
					Data = lineup,

					Title = lineup.Name,
					SubTitle = lineup.Description,

					HasAnalyze = true,

					IsEditEnabled = Lineup.CanEdit( user ),
					IsAnalyzeEnabled = lineup.CanAnalyze( user ),

					IsTappable = false,
					AnalyzeTapped = OnAnalyzeTapped,
					EditTapped = OnEditTapped
				};

				card.Init();
				
				List<Player> players = lineup.HasPhoto() ? lineup.GetPlayers() : null;

				// Populate player images
				card.SetPlayers( players );

				AddCard( card );
			}

			// Add card for creating new objects
			if ( Lineup.CanCreate( season, user ) )
			{
				AddNewCard( "lineup", CardSmall.CardHt );
			}
		}
	}

	/* Event Callbacks */

	// Called back when 'Add New' tapped
	protected override void OnNewCardTapped( DXCard card )
	{
		if ( data is Season season )
		{
			// Must have at least 6 players on roster
			if ( season.Players.Count < Lineup.BaseEntries )
			{
				DXAlert.ShowError( "lineup.err.count", OnErrorConfirmed );
			}
			else
			{
				LineupForm form = new( null, season );

				// Open in create mode
				Shell.Instance.ShowForm( form );
			}
		}
	}

	// User acknowledged error
	private void OnErrorConfirmed()
	{
		DXSpinner.Stop();

		Reset();
	}

	// Called back when card analyze button tapped
	private async void OnAnalyzeTapped( DXCard card )
	{
		if ( (card.Data is Lineup lineup) && (data is Season season) )
		{
			Shell shell = Shell.Instance;

			// Show dashboard with aggregated data
			shell.DashboardForm.Init( new DashboardConfig
			{
				Scope = DataConfig.LineupScope,
				ScopeName = lineup.Name,
				ScopeObject = lineup,

				Organization = season.Organization,

				Team1 = season.Team,
				Team2 = null
			});

			await shell.ShowDashboardForm( lineup.Name );
		}
	}

	// Called back when card edit button tapped
	private void OnEditTapped( DXCard card )
	{
		Lineup lineup = card.Data as Lineup;
		Season season = data as Season;

		LineupForm form = new( lineup, season );

		// Open in edit mode
		Shell.Instance.ShowForm( form );
	}
}

//
