using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PCUT.Extensions
{
    public static class EnumerableExtension
    {
        public static void Filter<T>(this ObservableCollection<T> collection, IList<T> data, Predicate<T> filter, int startIndex = 0)
        {
            int currentIndex = startIndex;
            var current = currentIndex < collection.Count ? collection[currentIndex] : default;
            int i = startIndex;
            while (i < data.Count() && currentIndex < collection.Count)
            {
                var item = data[i];
                var isValidItem = filter(item);
                var isCurrentItem = EqualityComparer<T>.Default.Equals(item, current);
                if (isValidItem)
                {
                    currentIndex++;
                    if (!isCurrentItem)
                        collection.Insert(currentIndex - 1, item);
                    else
                        current = currentIndex < collection.Count ? collection[currentIndex] : default;
                }
                else if (isCurrentItem)
                {
                    collection.RemoveAt(currentIndex);
                    current = currentIndex < collection.Count ? collection[currentIndex] : default;
                }
                i++;
            }
            while (i < data.Count)
            {
                var item = data[i];
                if (filter(item))
                    collection.Add(item);
                i++;
            }
        }
    }
}
