using System.Linq;
using System.Windows;
using Syncfusion.Data;
using Syncfusion.UI.Xaml.Grid;
using Syncfusion.UI.Xaml.Grid.Cells;
namespace InABox.DynamicGrid;

public class DynamicGridAggregateRenderer : GridTableSummaryCellRenderer
{
    public override void OnUpdateEditBinding(DataColumnBase dataColumn, GridTableSummaryCell element, object dataContext)
    {
        if (DataGrid == null)
            return;

        var record = dataContext as SummaryRecordEntry;
        if (record == null || record.SummaryRow == null)
            return;

        foreach (var summaryColumn in record.SummaryRow.SummaryColumns)
        {
            if (!summaryColumn.MappingName.Equals(dataColumn.GridColumn.MappingName))
                continue;
            
            var format = summaryColumn.Format.Replace("{", "").Replace("}", "").Split(':');
            var cmd = format.FirstOrDefault();
            var fmt = format.Length > 1 ? string.Join(":", format.Skip(1)) : "";
            
            var agg = SummaryCreator.GetSummaryAggregate(summaryColumn, DataGrid.View) as IDynamicGridSummaryAggregate;
            if (agg != null)

                element.Content = agg.Format(cmd, fmt);
            else
                base.OnUpdateEditBinding(dataColumn, element, dataContext);
        }
    }
}
