using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using InABox.Core;
using InABox.WPF;
using Microsoft.Xaml.Behaviors;

namespace InABox.DynamicGrid;

public class DynamicGridTimeStampColumn : DynamicGridMaskColumn<TimestampEditor>
{
    protected override Behavior CreateBehaviour() => 
        new TextBoxDateTimeMaskBehavior(Definition?.Format, false);

    protected override IValueConverter CreateConverter() =>
        new DateTimeToStringConverter(Definition?.Format);
    
    protected override void UpdateButtons(object? value, DynamicGridMaskColumnButton[]? buttons)
    {
        if (value is DateTime datetime && buttons?.Any() == true)
        {
            foreach (var button in buttons)
                button.Image = datetime.IsEmpty()
                    ? _set
                    : _clear;
        }
    }
    
    private readonly BitmapImage _clear = Wpf.Resources.delete.AsBitmapImage(20,20);
    private readonly BitmapImage _set = Wpf.Resources.tick.AsBitmapImage(20,20);
    
    protected override DynamicGridMaskColumnButton[]? CreateButtons()
    {
        return new DynamicGridMaskColumnButton[]
        {
            new DynamicGridMaskColumnButton()
            {
                Image = _set,
                Clicked = (sender,args) =>
                {
                    if (args.Value is DateTime datetime)
                    {
                        datetime = datetime.IsEmpty()
                            ? DateTime.Now
                            : DateTime.MinValue;
                        args.Value = datetime;
                        sender.Image = datetime.IsEmpty()
                            ? _set
                            : _clear;

                    }
                }
            }
        };
    }
    
    public DynamicGridTimeStampColumn(DynamicGridColumn definition) : base(definition)
    {
    }
}