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

namespace BS.Shared.Extensions
{
    public static class StringExtensions
    {
        public static bool ContainsAll(this string pString, IEnumerable<string> pToCheck)
        {
            string lLow = pString.ToLower();
            foreach (var iS in pToCheck)
            {
                if (!lLow.Contains(iS.Trim().ToLower()))
                {
                    return false;
                }
            }

            return true;
        }

        public static bool IsNullOrEmpty(this string pString)
        {
            return String.IsNullOrEmpty(pString);
        }

        public static List<string> Split(this string pString, string pSeparator)
        {
            if(pString == null)
                return new List<string>();

            return pString.Split(new[] { pSeparator }, StringSplitOptions.RemoveEmptyEntries).ToList();
        }

        public static IEnumerable<KeyValuePair<string, string>> SplitToKeyValuePairList(this string pString, string pSeparator1, string pSeperator2)
        {
            if(pString == null)
                return new KeyValuePair<string, string>[0];

            var preResult = pString.Split(pSeparator1);

            return preResult.Select(pair => new KeyValuePair<string, string>(pair.Split(pSeperator2)[0], pair.Split(pSeperator2)[1])).ToList();
        }

		public static string GetRecurrenceInfoAttribute(this string recurrenceInfo, string attribute)
		{
			using (var reader = XmlReader.Create(new StringReader(recurrenceInfo)))
			{
				reader.ReadToFollowing("RecurrenceInfo");
				reader.MoveToAttribute(attribute);
				
				return reader.Value;
			}
		}

		public static T GetValueFromDescription<T>(this string description)
		{
			var type = typeof(T);
			if (!type.IsEnum) throw new InvalidOperationException();
			foreach (var field in type.GetFields())
			{
				var attribute = Attribute.GetCustomAttribute(field,
					typeof(DescriptionAttribute)) as DescriptionAttribute;
				if (attribute != null)
				{
					if (attribute.Description == description)
						return (T)field.GetValue(null);
				}
				else
				{
					if (field.Name == description)
						return (T)field.GetValue(null);
				}
			}

			throw new ArgumentException("Not found.", "description");
		}
    }
}