using CommonAI.Zone.Instance;
using CommonLang;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace CommonAI.Zone.Helper
{

    public class DoAndRemoveCollection
    {
        public static void UpdateAndRemove<T>(LinkedList<T> list, Predicate<T> test)
        {
            using (var removed = ListObjectPool<LinkedListNode<T>>.AllocAutoRelease())
            {
                for (LinkedListNode<T> it = list.Last; it != null; it = it.Previous)
                {
                    T t = it.Value;
                    if (test(t))
                    {
                        removed.Add(it);
                    }
                }
                if (removed.Count > 0)
                {
                    foreach (LinkedListNode<T> it in removed)
                    {
                        list.Remove(it);
                    }
                }
            }
        }

        public static void UpdateAndRemove<T>(ICollection<T> list, Predicate<T> test)
        {
            using (var removed = ListObjectPool<T>.AllocAutoRelease())
            {
                foreach (T t in list)
                {
                    if (test(t))
                    {
                        removed.Add(t);
                    }
                }
                if (removed.Count > 0)
                {
                    for (int i = removed.Count - 1; i >= 0; --i)
                    {
                        list.Remove(removed[i]);
                    }
                }
            }
        }

        public static void UpdateAndRemove<T>(IList<T> list, Predicate<T> test)
        {
            using (var removed = ListObjectPool<T>.AllocAutoRelease())
            {
                for (int i = list.Count - 1; i >= 0; --i)
                {
                    T t = list[i];
                    if (test(t))
                    {
                        removed.Add(t);
                    }
                }
                if (removed.Count > 0)
                {
                    for (int i = removed.Count - 1; i >= 0; --i)
                    {
                        list.Remove(removed[i]);
                    }
                }
            }
        }
    }
}