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

namespace ChatController.Extensions
{
    public static class IDictionaryTExtensions
    {
        public static IDictionary<T, List<U>> AddOrUpdateValueInDictionary<T, U>(this IDictionary<T, List<U>> pDictionary, T pKey, List<U> pValue)
        {
            if (!pDictionary.ContainsKey(pKey))
            {
                pDictionary.Add(pKey, pValue);
            }
            else
            {
                pDictionary[pKey] = pDictionary[pKey].Union(pValue).ToList();
            }

            return pDictionary;
        }

        public static IDictionary<T, List<U>> AddOrUpdateValueInDictionary<T, U>(this IDictionary<T, List<U>> pDictionary, T pKey, U pValue)
        {
            if (!pDictionary.ContainsKey(pKey))
            {
                pDictionary.Add(pKey, new List<U> { pValue });
            }
            else
            {
                pDictionary[pKey].AddIfNotIn(pValue);
            }

            return pDictionary;
        }

        public static void AddAndIgnoreDuplicates<T, U>(this IDictionary<T, U> pDictionary, T pKey, U pValue)
        {
            if (pDictionary.ContainsKey(pKey))
            {
                return;
            }

            pDictionary.Add(pKey, pValue);
        }

        public static void AddAndIgnoreDuplicates<T, U>(this IDictionary<T, U> pDictionary, IEnumerable<KeyValuePair<T, U>> pDictionary2Add)
        {
            foreach (var kvp in pDictionary2Add.Where(kvp => !pDictionary.ContainsKey(kvp.Key)))
            {
                pDictionary.Add(kvp);
            }
        }
    }
}
