/* 
 * 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;

/*
 * Displays a stat report showing a Summary data grid. The grid can be toggled between set/match stats and between
 * primary team and opponent.
 */
public class ReportDrawerView : DXContent
{
	/* Constants */
	private const string SetKey = "set";
	private const string MatchKey = "match";
	
	private const string Team1Key = "team1";
	private const string Team2Key = "team2";
	
	/* Properties */

	// Display larger segment bars?
	public bool LargeBars { get; set; }

	// Font size for all grid cells
	public double TextSize { get; set; }

	/* Fields */
	private readonly DXGridLayout layout;

	private readonly DXSegmentBar scopeBar;
	private readonly DXSegmentBar teamBar;

	private Grid grid;

	// Config
	private JsonGrid json;
	private DataConfig config;

	private Set reportSet;

	/* Methods */
	public ReportDrawerView()
	{
		Padding = 0;

		// Layout
		layout = new DXGridLayout
		{
			IsClippedToBounds = true,

			Padding = 0,
			BackgroundColor = DXColors.Dark2
		};

		Content = layout;

		// Match/Set
		scopeBar = new DXSegmentBar
		{
			Mode = DXSegmentBar.SegmentMode.Text,
			SegmentFont = DXFonts.RobotoItalic,

			FillColor = DXColors.Dark3,
			TextColor = DXColors.Light4,
			SelectColor = DXColors.Light4,

			Horizontal = LayoutOptions.End,
			Vertical = LayoutOptions.Center,

			Selected = OnScopeSelected
		};

		scopeBar.Init();

		// Static text
		scopeBar.AddSegmentText( SetKey, DXString.GetUpper( "set.singular" ) );
		scopeBar.AddSegmentText( MatchKey, DXString.GetUpper( "match.singular" ) );

		// Always start with Set
		scopeBar.SelectKey( SetKey );
		
		// Team/Opponent
		teamBar = new DXSegmentBar
		{
			Mode = DXSegmentBar.SegmentMode.Text,
			SegmentFont = DXFonts.RobotoItalic,

			FillColor = DXColors.Dark3,
			TextColor = DXColors.Light4,
			SelectColor = DXColors.Light4,

			Horizontal = LayoutOptions.Start,
			Vertical = LayoutOptions.Center,

			Selected = OnTeamSelected
		};

		teamBar.Init();

		// Text set dynamically later
		teamBar.AddSegmentText( Team1Key );
		teamBar.AddSegmentText( Team2Key );

		// Always start with Team1
		teamBar.SelectKey( Team1Key );
		
		// Defaults
		TextSize = 14;
	}

	// Post construction initialization
	public async Task Init( Set set )
	{
		reportSet = set;

		// Parse JSON
		json = await DXResource.ReadJson<JsonGrid>( "Dashboards/drawer.json" );

		// Initially empty grid
		CreateGrid();

		// Opponent stats NA for Legacy engine
		if ( set.Legacy )
		{
			teamBar.Disable( Team2Key, true );
		}

		Match match = set.Match;

		// Set team labels
		teamBar.SetText( Team1Key, match.Team1Abbrev );
		teamBar.SetText( Team2Key, match.Team2Abbrev );

		// Starting options (set scope, primary team)
		config = new DataConfig
		{
			Scope = DataConfig.SetScope,
			ScopeObject = set,

			Type = AnalyzeKeys.GridKey,

			Organization = match.Season.Organization,
			IsTeam1 = true,

			Team1 = match.Team1,
			Team2 = match.Opponent,

			OuterDim = GetOuterDim( true ),
			InnerDim = null,

			OuterFilter = null,
			InnerFilter = null,
			PlayerAccessId = null,

			MaxLabelLen = 15
		};
	}

	// Returns dimension to be used for watch report
	private string GetOuterDim( bool team1 )
	{
		// Opponent or Rally-LOW uses rotation
		return (!team1 || reportSet.IsRallyLow) ? KeyDimension.RotationKey : KeyDimension.PlayerKey;
	}

	// Loads initial stat snapshot
	public async Task Load()
	{
		await UpdateData();
	}

	// Adds new stat to cache (recalculates and redraws)
	public async Task Add()
	{
		await UpdateData();
	}

	// Modifies existing stat in cache (recalculates and redraws)
	public async Task Modify()
	{
		await UpdateData();
	}

	// Removes stat from cache (recalculates and redraws)
	public async Task Remove()
	{
		await UpdateData();
	}

	// (Re)creates and reloads data into grid
	private async Task UpdateData()
	{
		layout.Remove( grid );

		// Must (re)create grid
		CreateGrid();

		// Filter for scope/team
		DataStats stats = await DataFilter.Filter( config );

		// Accumulate and calculate all stats
		await DataDimension.ProcessDimension( config, stats );

		// Populate
		await grid.UpdateData( config );
	}

	// (Re)creates data grid on first launch or dynamic update
	private void CreateGrid()
	{
		// Create
		grid = new Grid
		{
			TextSize = TextSize,
			AllowResizingColumns = false,

			Margin = 0,
			BackgroundColor = DXColors.Dark2,

			HorizontalOptions = LayoutOptions.Fill,
			VerticalOptions = LayoutOptions.Start
		};

		// Initialize
		grid.Init( json );

		UpdateLayout();
	}

	/* Event Callbacks */

	// User selected set/match scope
	private async void OnScopeSelected( string key )
	{
		config.Scope = key;

		// Update configuration
		config.ScopeObject = (key == SetKey) ? reportSet : reportSet.Match;

		// Ignore internal selection
		await UpdateData();
	}

	// User selected primary/opponent team
	private async void OnTeamSelected( string key )
	{
		bool team1 = (key == Team1Key);

		// Update configuration
		config.IsTeam1 = team1;
		config.OuterDim = GetOuterDim( team1 );

		// Ignore internal selection
		await UpdateData();
	}

	/* Layout */

	// Must recreate grid for new orientation
	public override async void Rotate()
	{
		await UpdateData();
	}

	// Landscape (4:3)
	protected override void Landscape()
	{
		if ( reportSet != null )
		{
			LayoutCommon( 0.117, (DXDevice.IsLargeTablet() ? 0.033 : 0.031) );
		}
	}

	// Portrait (3:4)
	protected override void Portrait()
	{
		if ( reportSet != null )
		{
			LayoutCommon( 0.117, 0.035 );
		}
	}

	// Widescreen Landscape (16:10)
	protected override void WideLandscape()
	{
		LayoutCommon( (reportSet.Legacy ? 240 : 200), 0.035 );
	}

	// Widescreen Portrait (10:16)
	protected override void WidePortrait()
	{
		LayoutCommon( 70, 0.035 );
	}

	// Mobile Portrait
	protected override void MobilePortrait()
	{
		LayoutCommon( 0.130, 0.035 );
	}

	// Mobile Landscape
	protected override void MobileLandscape()
	{
		LayoutCommon( 0.150, 0.035 );
	}

	// Common layout for all tablet devices
	private void LayoutCommon( double firstColWd, double rowHt )
	{
		if ( reportSet == null )
		{
			return;
		}

		double dim = DXDevice.GetScreenDim();

		bool mobile = DXDevice.IsMobile;
		bool largeBars = LargeBars || (reportSet.Legacy && !mobile);

		layout.ClearAll();

		double barWd = mobile ? 64 : 70;
		double barHt = largeBars ? 26 : 20;

		double barRow = largeBars ? (barHt + 15) : barHt;
		double barFont = largeBars ? 15 : 12;
		const double barPad = 30;

		// 2 rows, 2 columns
		layout.AddFixedRow( barRow );   // 0: scope, team
		layout.AddStarRow();            // 1: grid

		layout.AddStarColumn();         // 0: scope
		layout.AddStarColumn();         // 1: team

		double topPad = largeBars ? 5 : 3;

		// Scope
		scopeBar.WidthRequest = (barWd * 2);
		scopeBar.Margin = new Thickness( 0, topPad, barPad, 0 );

		scopeBar.SegmentWd = barWd;
		scopeBar.SegmentHt = barHt;
		scopeBar.SegmentFontSize = barFont;

		layout.Add( scopeBar, 0, 0 );

		// Team
		teamBar.WidthRequest = (barWd * 2);
		teamBar.Margin = new Thickness( barPad, topPad, 0, 0 );

		teamBar.SegmentWd = barWd;
		teamBar.SegmentHt = barHt;
		teamBar.SegmentFontSize = barFont;

		layout.Add( teamBar, 1, 0 );

		// Grid
		grid.FixedFirstWd = (dim * firstColWd);
		grid.RowHt = (dim * rowHt);

		layout.Add( grid, 0, 1, 2, 1 );
	}
}

//
