using System;
using System.Collections.Generic;
using System.Windows.Data;
using System.Windows.Media;
using InABox.Core;
using InABox.Wpf;
using Syncfusion.Data;
using Syncfusion.UI.Xaml.Grid;
using Syncfusion.UI.Xaml.TreeGrid;

namespace InABox.DynamicGrid;

public class DynamicGridCurrencyColumn : DynamicGridNumericColumn<CurrencyEditor, GridCurrencyColumn, TreeGridCurrencyColumn>
{

    protected override void Configure(GridCurrencyColumn column, CurrencyEditor editor)
    {
        column.CurrencyDecimalDigits = GetDigits(editor);
        column.CurrencySymbol = string.IsNullOrEmpty(editor.CurrencySymbol) ? "$" : $"{editor.CurrencySymbol} ";
        column.CurrencyGroupSeparator = ",";
        column.CurrencyGroupSizes = new Int32Collection(new[] { 3, 3, 3, 3, 3, 3 });
    }

    protected override void Configure(TreeGridCurrencyColumn column, CurrencyEditor editor)
    {
        column.CurrencyDecimalDigits = GetDigits(editor);
        column.CurrencySymbol = string.IsNullOrEmpty(editor.CurrencySymbol) ? "$" : $"{editor.CurrencySymbol} ";
        column.CurrencyGroupSeparator = ",";
        column.CurrencyGroupSizes = new Int32Collection(new[] { 3, 3, 3, 3, 3, 3 });
    }

    protected override void UpdateBinding(TreeGridCurrencyColumn column)
    {
        base.UpdateBinding(column);
        (column.ValueBinding as Binding).Converter = new FuncConverter<object?, decimal?>(
            x =>
            {
                if(x is null)
                {
                    return null;
                }
                else
                {
                    return Convert.ToDecimal(x);
                }
            },
            x =>
            {
                return x.HasValue ? (double)x.Value : null;
            });
    }

    public override IDynamicGridSummary? Summary()
    {
        if (Definition.Editor.Summary == Core.Summary.None)
            return null;
        
        return Definition.Editor.Summary == Core.Summary.Sum
            ? new DynamicGridSumSummary<double>($"C{Editor!.Digits}")
            : new DynamicGridCountSummary();
    }

    public DynamicGridCurrencyColumn(DynamicGridColumn definition) : base(definition)
    {
    }
}