using System.Collections.Specialized;
using System.Windows.Controls;
using System.Windows.Threading;
using ConeCalorimeter.ViewModels;

namespace ConeCalorimeter.Views;

public partial class RealtimeDataView : UserControl
{
    private INotifyCollectionChanged? _rowsCollection;

    public RealtimeDataView()
    {
        InitializeComponent();
        DataContextChanged += (_, _) => SubscribeRowsCollection();
        Unloaded += (_, _) => UnsubscribeRowsCollection();
    }

    private void SubscribeRowsCollection()
    {
        UnsubscribeRowsCollection();

        if (DataContext is RealtimeDataViewModel viewModel)
        {
            _rowsCollection = viewModel.Rows;
            _rowsCollection.CollectionChanged += RowsCollectionChanged;
        }
    }

    private void UnsubscribeRowsCollection()
    {
        if (_rowsCollection is not null)
        {
            _rowsCollection.CollectionChanged -= RowsCollectionChanged;
            _rowsCollection = null;
        }
    }

    private void RowsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action != NotifyCollectionChangedAction.Add || e.NewItems is null || e.NewItems.Count == 0)
        {
            return;
        }

        var latest = e.NewItems[e.NewItems.Count - 1];
        Dispatcher.BeginInvoke(new Action(() => RealtimeDataGrid.ScrollIntoView(latest)), DispatcherPriority.Background);
    }
}
