using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using InABox.Core;
using InABox.WPF;
using Microsoft.Xaml.Behaviors;
using Syncfusion.Data;
using Syncfusion.UI.Xaml.Grid;
using Syncfusion.UI.Xaml.Grid.Cells;

namespace InABox.DynamicGrid;

public class DynamicGridDurationColumn : DynamicGridMaskColumn<DurationEditor> 
{
    protected override Behavior CreateBehaviour() => 
        new TextBoxTimeSpanMaskBehavior(Definition.Format);

    protected override IValueConverter CreateConverter() =>
        new TimeSpanToStringConverter(Definition.Format);
    
    private readonly BitmapImage _less = Wpf.Resources.downarrow.AsBitmapImage(20,20);
    private readonly BitmapImage _more = Wpf.Resources.uparrow.AsBitmapImage(20,20);
    
    protected override DynamicGridMaskColumnButton[]? CreateButtons()
    {
        return new DynamicGridMaskColumnButton[]
        {
            new DynamicGridMaskColumnButton()
            {
                Image = _less,
                Clicked = (sender,args) =>
                {
                    if (args.Value is TimeSpan time)
                    {
                        time = time.Subtract(TimeSpan.FromMinutes(15));
                        if (time.Ticks < 0)
                            time = TimeSpan.Zero;
                        args.Value = time;
                    }
                },
                Position = DynamicGridMaskColumnButtonPosition.Left
            },
            new DynamicGridMaskColumnButton()
            {
                Image = _more,
                Clicked = (sender,args) =>
                {
                    if (args.Value is TimeSpan time)
                    {
                        time = time.Add(TimeSpan.FromMinutes(15));
                        args.Value = time;
                    }
                },
                Position = DynamicGridMaskColumnButtonPosition.Right
            }
        };
    }
    
    public override IDynamicGridSummary? Summary()
    {
        if (Definition.Editor.Summary == Core.Summary.None)
            return null;
        
        return Definition.Editor.Summary == Core.Summary.Sum
            ? new DynamicGridSumSummary<TimeSpan>(Definition.Format.IsNullOrWhiteSpace() ? "" : Definition.Format.Replace(":", "':'"))
            : new DynamicGridCountSummary();
    }

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