namespace HistoryView.Controls;

public partial class WarningItemCollection : UserControl
{
    public WarningItemCollection()
    {
        InitializeComponent();
    }

    public AlarmInfo Latest
    {
        get { return (AlarmInfo)GetValue(LatestProperty); }
        set { SetValue(LatestProperty, value); }
    }

    public static readonly DependencyProperty LatestProperty =
        DependencyProperty.Register("Latest", typeof(AlarmInfo), typeof(WarningItemCollection), new PropertyMetadata(default));

    public ObservableDictionary<byte,AlarmInfo> Alarms
    {
        get { return (ObservableDictionary<byte, AlarmInfo>)GetValue(AlarmsProperty); }
        set { SetValue(AlarmsProperty, value); }
    }

    public static readonly DependencyProperty AlarmsProperty =
        DependencyProperty.Register("Alarms", typeof(ObservableDictionary<byte, AlarmInfo>), typeof(WarningItemCollection), new PropertyMetadata(default, PropertyChangedCallback));

    private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is not WarningItemCollection warningCollection)
            return;

        if (e.NewValue is not ObservableDictionary<byte, AlarmInfo> and || and is null)
            return;

        and.CollectionChanged += And_CollectionChanged;

        if (and.Any())
            warningCollection.Latest = and.LastOrDefault()!.Value;

    }

    private static void And_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        if (sender is not WarningItemCollection warningCollection)
            return;

        if (e.NewItems is not IEnumerable<AlarmInfo> and || and is null)
            return;

        if (and.Any())
            warningCollection.Latest = and.LastOrDefault()!;
    }

    public ICommand Clear
    {
        get { return (ICommand)GetValue(ClearProperty); }
        set { SetValue(ClearProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Clear.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ClearProperty =
        DependencyProperty.Register("Clear", typeof(ICommand), typeof(WarningItemCollection), new PropertyMetadata(default));
}
