using System;
using System.Collections.Generic;
using System.Linq;

namespace BS.Shared.Extensions
{
    public static class IListTExtensions
    {
        public static void AddIfNotIn<T>(this IList<T> pList, T pToAdd)
        {
            if (!pList.Contains(pToAdd))
            {
                pList.Add(pToAdd);
            }
        }

	    public static void AddRangeIfElementsNotIn<T>(this IList<T> pList, IEnumerable<T> pToAdd)
	    {
			foreach (var iItem in pToAdd)
			{
				pList.AddIfNotIn(iItem);
			}
	    }

        public static void AddRange<T>(this IList<T> pList, IEnumerable<T> pToAdd)
        {
            foreach (T iItem in pToAdd)
            {
                pList.Add(iItem);
            }
        }

        public static bool Exists<T>(this IList<T> pList, Predicate<T> pMatch)
        {
            foreach (T iItem in pList)
            {
                if (pMatch(iItem))
                {
                    return true;
                }
            }

            return false;
        }

        public static void MakeEqualTo<T>(this IList<T> plist, IList<T> otherList)
        {
            var toRemove = new List<T>();

            foreach (T t in plist)
            {
                if (!otherList.Contains(t))
                {
                    toRemove.Add(t);
                }
            }

            plist.RemoveRange(toRemove);

            foreach (T t in otherList)
            {
                if (!plist.Contains(t))
                {
                    plist.Insert(otherList.IndexOf(t), t);
                }
            }
        }

        public static void RemoveRange<T>(this IList<T> pList, IEnumerable<T> pToRemove)
        {
            foreach (T iItem in pToRemove.ToList())
            {
                pList.Remove(iItem);
            }
        }

        public static void RemoveRange<T>(this IList<T> pList, Predicate<T> pMatch)
        {
            List<T> lToDelete = pList.Where(t => pMatch(t)).ToList();
            pList.RemoveRange(lToDelete);
        }
    }
}