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

using DXLib.Utils;

namespace iStatVball3;

/*
 * Helper class responsible for processing all data necessary to populate a BarChart bar graph. Stats are aggregated,
 * accumulated, and calculated here.
 */
public class BarChart
{
	/* Properties */

	// External ref
	public BarView View { get; set; }

	/* Fields */
	private JsonBar jsonBar;

	/* Methods */

	// Post construction initialization
	public void Init( JsonBar json )
	{
		jsonBar = json;
	}

	// Calculates and displays all bar chart data
	public void UpdateData( DataConfig config )
	{
		View.Clear();

		// Calculate
		List<BarDatum> data = GenerateData( config );

		string label = DXString.Get( GetResource( config ) );

		// Display
		View.SetSeries( data, label );
	}

	// Creates bar chart data set
	private List<BarDatum> GenerateData( DataConfig config )
	{
		List<BarDatum> data = [];

		// Metrics already calculated
		DataDimension dimension = config.Dimension;

		// Build each player/rotation bar
		foreach ( DataMetrics metrics in dimension.Metrics.Values )
		{
			float attempts = metrics.GetFloat( jsonBar.Attempt );

			// Only include if there were attempts
			if ( attempts > 0 )
			{
				string label = metrics.Label;
				float value = metrics.GetFloat( jsonBar.Metric );

				// Create data point
				BarDatum datum = new( label, value );
				data.Add( datum );
			}
		}

		// Sort with highest bar value first
		List<BarDatum> sorted = data.OrderByDescending( bd => bd.Value ).ToList();

		string teamLabel = DXString.GetUpper( "bar.team" );
		float teamValue = config.Totals.GetFloat( jsonBar.Metric );

		// Create team data point (always first)
		BarDatum teamDatum = new( teamLabel, teamValue );
		sorted.Insert( 0, teamDatum );

		return sorted;
	}

	// Returns resource string for dimension specific axis label
	private string GetResource( DataConfig config )
	{
		return config.OuterDim switch
		{
			KeyDimension.PlayerKey => "dimension.player",
			KeyDimension.RotationKey => "dimension.rotation",

			_ => null,
		};
	}
}

//
