/* 
 * 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;
using DXLib.Data;

namespace iStatVball3;

/*
 * Card page for list of seasons within a parent team.
 */
public class SeasonPage : CardPage
{
	/* Fields */
	private PurchaseView purchaseView;

	/* Methods */
	public SeasonPage( Team team ) : base( team )
	{
		Title = DXString.Get( "season.plural" );
	}

	/* Abstracts */

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

		Team team = data as Team;

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

		// Sort newest season first
		List<Season> seasons = Season.CanView( team ).OrderByDescending( s => s.StartDate ).ToList();

		// Add card for each season
		foreach ( Season season in seasons )
		{
			CardLarge card = new()
			{
				Data = season,

				DefaultIcon = "season",
				ImageUrl = season.ImageUrl,
				ImageColor = season.Color,

				Title = season.Name,
				SubTitle = season.Result,

				Count = season.MatchCount,
				CountTitle = "match",

				HasAnalyze = true,

				IsEditEnabled = Season.CanEdit( user ),
				IsAnalyzeEnabled = season.CanAnalyze( user ),

				CardTapped = OnCardTapped,
				AnalyzeTapped = OnAnalyzeTapped,
				EditTapped = OnEditTapped,

				ShowSpinner = DXData.HasConnection()
			};
			
			card.Init();
			
			// 'Won-Lost-Tied'
			if ( season.IsPopulated )
			{
				card.UpdateRecord( season.Won, season.Lost, season.Tied );
			}

			AddCard( card );
		}

		// Add card for creating new objects
		if ( Season.CanCreate( team, user ) )
		{
			AddNewCard( "season", CardLarge.CardHt );
		}

		// No longer need sync
		Shell.Instance.ToolBar.RemoveCustom( 1 );

		// Invalidate launch cache
		DXPreferences.Set( "launch.path", null );
	}

	/* Event Callbacks */

	// Called back when 'Add New' tapped
	protected override void OnNewCardTapped( DXCard card )
	{
		// Network connection required
		if ( !DXData.HasConnection() )
		{
			DXAlert.ShowNetworkError( "net.err.season", OnDone );
			return;
		}
		
		User user = Shell.CurrentUser;

		// Validate purchase
		bool purchased = PurchaseEngine.HasPurchased( user );
		
		// Has not started free trial yet (and never purchased)
		if ( !PurchaseEngine.IsTrialUsed( user ) && !purchased )
		{
			DXAlert.ShowOkCancel( "purchase.trial", "purchase.trial.msg", OnCreate, OnDone );
			return;
		}
		
		bool trial = PurchaseEngine.IsTrialPeriod( user );
		bool remaining = PurchaseEngine.HasAvailable( user );
		
		// Still within free trial period, but already created season
		if ( trial && !remaining )
		{
			DXAlert.ShowOkCancel( "purchase.limit", "purchase.limit.msg", OnPurchase, OnDone );
			return;
		}
		
		// Trial ended, no purchases
		if ( !trial && !purchased )
		{
			DXAlert.ShowOkCancel( "purchase.end", "purchase.end.msg", OnPurchase, OnDone );
			return;
		}
		
		// Available Team-Seasons, OK to proceed
		if ( remaining )
		{
			OnCreate();
		}
		// No Team-Seasons remaining, must purchase
		else
		{
			DXAlert.ShowOkCancel( "purchase.empty", "purchase.empty.msg", OnPurchase, OnDone );
		}
	}

    // OK to proceed with season creation
    private void OnCreate()
	{
		// Might have just completed purchase
		purchaseView?.Hide();
		
		Team team = data as Team;
		SeasonForm form = new( null, team );
		
		// Open in create mode
		Shell.Instance.ShowForm( form );
	}

	// Display purchase options for user
	private async void OnPurchase()
	{
		// Create purchase UI
		purchaseView = new PurchaseView()
		{
			Completed = OnCreate,
			Cancelled = OnDone
		};
		
		await purchaseView.ShowProducts();
	}

	// User cancelled purchase process, reset cards
	private void OnDone()
	{
		DXSpinner.Stop();

		Reset();
	}

	// Called back when normal card tapped
	private static async void OnCardTapped( DXCard card )
	{
		if ( card.Data is Season season )
		{
			HomePage page = new( season );
		
			// Populate
			await season.PopulateFull();
		
			// Navigate to season home page for selected season
			if ( DXData.HasConnection() || (season.Players.Count > 0) )
			{
				Shell.Instance.PageStack.Push( page, season.Name );
			}
			// Must have connection or already be populated
			else
			{
				DXSpinner.Stop();
		
				DXAlert.ShowNetworkError( "net.err.home", card.Reset );
			}
		}
	}

	// Called back when card analyze button tapped
	private void OnAnalyzeTapped( DXCard card )
	{
		// User already warned about performance
		if ( DXPreferences.Get( "season.warned", false ) )
		{
			OnAnalyzeConfirmed( card );
		}
		// Warn user
		else
		{
			DXAlert.ShowOkCancel( "analyze.perf", "analyze.perf.msg", () => OnAnalyzeConfirmed( card ), card.Reset );

			// Only warn once
			DXPreferences.Set( "season.warned", true );
		}
	}

	// User acknowledged performance warning
	private static async void OnAnalyzeConfirmed( DXCard card )
	{
		Shell shell = Shell.Instance;
		
		if ( card.Data is Season season )
		{
			// Show dashboard metrics
			shell.DashboardForm.Init( new DashboardConfig
			{
				Scope = DataConfig.SeasonScope,
				ScopeName = season.Name,
				ScopeObject = season,

				Organization = season.Organization,

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

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

	// Called back when card edit button tapped
	private void OnEditTapped( DXCard card )
	{
		Season season = card.Data as Season;
		Team team = data as Team;
		
		SeasonForm form = new( season, team );
		
		// Open in edit mode
		Shell.Instance.ShowForm( form );
	}
}

//
