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

namespace BS.Shared.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].Add(pValue);
			}

			return pDictionary;
		}

		// Nur im DEBUG Mode
	    public static void WoerterbuchAufDesktopSpeichern<T, U>(this IEnumerable<KeyValuePair<T, List<U>>> pDictionary)
	    {
#if DEBUG
			
		    var sw = new StreamWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Woerterbuch.txt"), true);

			sw.WriteLine("{0} --------------------------------------------------", DateTime.Now);
		    foreach (var kvp in pDictionary)
		    {
				sw.WriteLine("{0}: ", kvp.Key);
			    foreach (var listElement in kvp.Value)
			    {
					sw.WriteLine("{0}", listElement);
			    }
				sw.WriteLine();
		    }
			sw.WriteLine("----------------------------------------------------------------------");
			sw.Flush();
		    sw.Close();
#endif
	    }

	    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);
            }
        }
    }
}
