using SWRIS.Dtos;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;

namespace SWRIS.Models.ViewModel
{
    public class RopeViewBaseModel : INotifyPropertyChanged
    {
        private ObservableCollection<SimpleRecordDto> records;
        public ObservableCollection<SimpleRecordDto> Records
        {
            get => records;
            set
            {
                if (records != value)
                {
                    records = value;
                    OnPropertyChanged(nameof(Records));
                }
            }
        }
        public void AddRecord(SimpleRecordDto record)
        {
            record.IsNew = true;
            SafeCollectionInsert(Records, 0, record);
            // 延迟重置 IsNew 状态，避免重复触发动画
            var timer = new System.Windows.Threading.DispatcherTimer
            {
                Interval = System.TimeSpan.FromSeconds(3)
            };
            timer.Tick += (s, e) =>
            {
                record.IsNew = false;
                timer.Stop();
            };
            timer.Start();
        }
        protected void SafeCollectionInsert<T>(ObservableCollection<T> collection, int index, T item)
        {
            if (Application.Current.Dispatcher.CheckAccess())
            {
                collection.Insert(index, item);
            }
            else
            {
                Application.Current.Dispatcher.Invoke(() => collection.Insert(index, item));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected internal virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
