using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Data.Converters;
using Avalonia.Layout;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InABox.Avalonia.Components;

public class AvaloniaDataGridNumericColumn<TEntity, TType> : AvaloniaDataGridColumn<TEntity, TType>
    where TType : struct, IComparable, IComparable<TType>, IConvertible, IEquatable<TType>, IFormattable
{
    public bool BlankIfZero { get; set; }

    public string Format { get; set; }

    public AvaloniaDataGridNumericColumn()
    {
        Width = GridLength.Auto;
        BlankIfZero = true;
    }

    // Summaries

    public override DataGridColumn CreateColumn()
    {
        var column = CreateColumn<DataGridTemplateColumn>();
        column.CellTemplate = new FuncDataTemplate<object?>((value, scope) =>
        {
            var label = new TextBlock
            {
                Margin = new(2, 0, 0, 0),
                TextAlignment = Alignment,
                VerticalAlignment = VerticalAlignment.Center
            };
            label.Bind(TextBlock.TextProperty, new Binding(ColumnName)
            {
                Converter = new FuncValueConverter<TType, string>(x => BlankIfZero && Equals(x, default(TType)) ? "" : string.Format($"{{0:{Format}}}", x))
            });
            return label;
        });
        return column;
    }
}
