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

using DXLib.Data.Model;
using DXLib.Utils;

namespace iStatVball3;

/*
 * Specialized card for Sets. Similar to CardSmall except with result badge and point totals. 
 */
public sealed class SetCard : CardBase
{
	/* Events */
	public Action<DXCard> RecordTapped { get; set; }

	/* Fields */
	private readonly DXTextBadge badge;
	private readonly DXLabel scoreLbl;

	private readonly DXButton recordBtn;
	private readonly DXIconButton videoBtn;

	/* Methods */
	public SetCard( Set set, bool readOnly = false ) : base( readOnly )
	{
		bool ios = DXDevice.IsIOS;
		bool tablet = DXDevice.IsTablet;
		bool wide = DXDevice.IsTabletWide;

		/* Layout */

		// 4 Rows
		layout.AddStarRow( 33 );        // 0: labels
		layout.AddStarRow( 14 );        // 1: badge
		layout.AddStarRow( 23 );        // 2: score
		layout.AddStarRow( 30 );        // 3: buttons

		// 2 columns
		layout.AddStarColumn( 62 );     // 0: other
		layout.AddStarColumn( 38 );     // 1: image/icon

		/* Controls */

		// Labels
		TitleSize = 24;
		SubTitleSize = 13;

		labels.SubTitleLbl.Font = DXFonts.Roboto;
		labels.SubTitleLbl.Margin = DXDevice.IsIOS ? 0 : new Thickness( 0, -7, 0, 0 );

		layout.Add( labels, 0, 0 );

		// Image/icon
		layout.Add( imageArea, 1, 0, 1, 3 );

		// Badge
		badge = new DXTextBadge
		{
			TextColor = DXColors.Light4,
			Margin = new Thickness( 10, 10, 10, 0 ),
			Horizontal = LayoutOptions.Start,

			Selected = OnBadgeSelected
		};

		badge.Adjust( 0, (tablet ? (wide ? -2 : 0) : (ios ? -1 : 0)) );

		layout.Add( badge, 0, 1 );

		// Score
		scoreLbl = new DXLabel
		{
			Font = DXFonts.Oswald,
			FontSize = 30,
			Margin = new Thickness( 10, (ios ? 0 : -10) ),

			VerticalTextAlignment = TextAlignment.Start
		};

		layout.Add( scoreLbl, 0, 2 );

		// Analyze/Edit buttons
		buttons.Margin = new Thickness( 10, 0, 10, 8 );
		buttons.Vertical = LayoutOptions.End;

		layout.Add( buttons, 0, 3, 2, 1 );

		// Lock
		if ( readOnly || GlobalLock )
		{
			layout.Add( lockBtn, 1, 3 );
		}

		/* Set Specific */

		Data = set;

		// Image
		DefaultIcon = "set";
		ImageUrl = set.ImageUrl;
		ImageColor = set.Match.Color;

		// Labels
		Title = set.Name;
		SubTitle = set.Detail;

		// Init colors
		Update( set );

		User user = Shell.CurrentUser;

		// Start/Resume
		if ( set.CanRecord( user ) && !set.IsEnded )
		{
			recordBtn = new DXButton
			{
				Margin = new Thickness( 0, 0, 0, 2 ),
				
				Resource = set.IsNew ? "set.start" : "set.resume",
				Type = DXButton.ButtonType.Positive,

				IsSticky = true,

				ButtonWd = 80,
				ButtonTapped = OnRecordTapped
			};

			recordBtn.Init();
			
			buttons.Add( recordBtn );
		}

		MatchVideo video = set.Match.Video;
		
		// Video (only if applicable)
		if ( (video != null) && video.CanView( Shell.CurrentUser ) )
		{
			if ( set.Synced && set.IsEnded )
			{
				videoBtn = new DXIconButton
				{
					Resource = "video_outline",
		
					IconColor = DXColors.Negative,
					IconScale = 1.3f,
		
					Size = 26,
					Margin = new Thickness( 0, 8, 12, 0 ),
		
					Horizontal = LayoutOptions.End,
					Vertical = LayoutOptions.Center,
		
					IsSticky = true,
					ButtonTapped = OnVideo
				};
		
				layout.Add( videoBtn, 1, 3 );
			}
		}
	}

	// Updates card fields without requiring page refresh
	public override void Update( DXModel model )
	{
		Set set = model as Set;

		UpdateBadge( set );
		UpdateScore( set );
	}

	// Sets badge text and color for current state
	private void UpdateBadge( Set set )
	{
		string resource;

		// RallySync
		if ( set.IsRallySynced && !set.IsEnded )
		{
			resource = "set.sync";
		}
		// In Progress
		else if ( set.IsInProgress )
		{
			resource = "set.progress";
		}
		// New
		else if ( set.IsNew )
		{
			resource = "set.new";
		}
		// Won
		else if ( set.Won )
		{
			resource = "set.won";
		}
		// Lost
		else if ( set.Lost )
		{
			resource = "set.lost";
		}
		// Tied
		else
		{
			resource = "set.tied";
		}

		badge.ResourceUpper = resource;
		badge.Color = GetColor( set );
	}

	// Sets score text and color
	private void UpdateScore( Set set )
	{
		// No score for new set
		if ( set.IsNew )
		{
			scoreLbl.IsVisible = false;
		}
		// 'X-Y' (green for win, else gray)
		else
		{
			scoreLbl.Text = $"{set.Points1}-{set.Points2}";
			scoreLbl.TextColor = GetColor( set );
			scoreLbl.IsVisible = true;
		}
	}

	// Returns color to be used for badge/score based on set state
	private static Color GetColor( Set set )
	{
		Color color;

		// Video Sync
		if ( set.IsRallySynced && !set.IsEnded )
		{
			color = DXColors.Negative;
		}
		// In Progress
		else if ( set.IsInProgress )
		{
			color = DXColors.Action;
		}
		// New
		else if ( set.IsNew )
		{
			color = DXColors.Warn;
		}
		// Won
		else if ( set.Won )
		{
			color = DXColors.Positive;
		}
		// Lost
		else if ( set.Lost )
		{
			color = DXColors.Dark4;
		}
		// Tied
		else
		{
			color = DXColors.Dark4;
		}

		return color;
	}

	// Resets record button sticky state
	public override void Reset()
	{
		base.Reset();

		recordBtn?.Reset();
	}

	// Required implementation
	public override double GetViewHt()
	{
		return CardSmall.CardHt;
	}

	// Used to exclude buttons from card tap area
	protected override bool IsChildBounds( Point point )
	{
		return base.IsChildBounds( point ) || ((recordBtn != null) && recordBtn.Bounds.Contains( point )) 
		                                   || ((videoBtn != null) && videoBtn.Bounds.Contains( point ));
	}

	/* Event Callbacks */

	// Pass through badge taps
	private void OnBadgeSelected()
	{
		HandleTap( badge.Bounds.Center );
	}

	// User tapped start/resume button, callback listener
	private void OnRecordTapped( object sender )
	{
		DXSpinner.Start();

		RecordTapped?.Invoke( this );
	}

	// Launch video filter tool
	private async void OnVideo()
	{
		if ( Data is Set set )
		{
			// Create tool
			VideoTool videoTool = new( set );

			// Launch
			await Shell.Instance.ShowTool( videoTool );
		}
	}

	/* Layout */

	// Device/orientation specific layout
	public override void UpdateLayout( LayoutType type )
	{
		base.UpdateLayout( type );
		
		// Must refresh Analyze here
		if ( Data is Set set )
		{
			User user = Shell.CurrentUser;
			
			IsAnalyzeEnabled = set.CanAnalyze( user ) && !set.IsNew;
		}

		videoBtn?.Reset();
	}
}

//
