using System.Collections;
using System.Text;

namespace PlcSiemens.Core.Extension
{
    /// <summary>集合扩展</summary>
    public static class CollectionExtension
    {
        /// <summary>
        /// 确保某一类型的元素必须位于开始位置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="checkedItem">想要位于首位的元素的类型</param>
        /// <returns>调整后的集合</returns>
        /// <remarks>
        /// 本方法适用于要确认的元素的类型在集合中唯一的情况。
        /// </remarks>
        public static void EnsureFirstPosition<T>(this IEnumerable<T> source, Type checkedItem)
        {
            if (source == null)
            {
                return;
            }
            var sourceArray = new List<T>(source);
            var itemIndex = sourceArray.FindIndex(m => m.GetType() == checkedItem);
            if (itemIndex <= 0) return;
            var changeItem = sourceArray[itemIndex];
            sourceArray.RemoveAt(itemIndex);
            sourceArray.Insert(0, changeItem);
            source = sourceArray;
        }

        /// <summary>
        /// 确保某一类型的元素必须位于末尾位置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="checkedItem">想要位于首位的元素的类型</param>
        /// <returns>调整后的集合</returns>
        /// <remarks>
        /// 本方法适用于要确认的元素的类型在集合中唯一的情况。
        /// </remarks>
        public static void EnsureLastPosition<T>(this IEnumerable<T> source, Type checkedItem)
        {
            if (source == null)
            {
                return;
            }
            var sourceArray = new List<T>(source);
            var itemIndex = sourceArray.FindIndex(m => m.GetType() == checkedItem);
            if (itemIndex == sourceArray.Count - 1) return;
            var changeItem = sourceArray[itemIndex];
            sourceArray.RemoveAt(itemIndex);
            sourceArray.Insert(sourceArray.Count - 1, changeItem);
            source = sourceArray;
        }

        /// <summary>
        /// 集合转换
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <typeparam name="TResult">转换后的对象</typeparam>
        /// <param name="items">对象</param>
        /// <param name="transformation">转换表达式</param>
        /// <returns></returns>
        public static IEnumerable<TResult> ConvertAll<T, TResult>(this IEnumerable<T> items,
            Converter<T, TResult> transformation)
        {
            if (items == null) return null;

            var arr = items as T[];
            if (arr != null)
            {
                return Array.ConvertAll(arr, transformation);
            }
            var list = items as List<T>;
            if (list != null)
            {
                return list.ConvertAll(transformation);
            }

            return items.Select(_ => transformation(_));
        }

        /// <summary>
        ///     Func转Predicate
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static Predicate<T> ToPredicate<T>(this Func<T, bool> source)
        {
            var result = new Predicate<T>(source);
            return result;
        }

        /// <summary>
        /// IEnumerable<T>对象的轮询操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="action"></param>
        public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
        {
            if (items == null)
            {
                return;
            }

            var arr = items as T[];
            if (arr != null)
            {
                Array.ForEach(arr, action);
                return;
            }
            var list = items as List<T>;
            if (list != null)
            {
                list.ForEach(action);
                return;
            }
            foreach (var item in items)
            {
                action(item);
            }
        }

        /// <summary>
        /// IEnumerable<T>是否为空
        /// </summary>
        /// <param name="targer"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this IEnumerable targer)
        {
            return targer == null || targer.GetEnumerator().MoveNext() == false;
        }

        /// <summary>
        ///     ICollection<T />转换成数组T[]
        /// </summary>
        public static T[] ToArray<T>(this ICollection<T> collection, int index = 0)
        {
            if (collection.IsNullOrEmpty()) return null;
            var arr = new T[collection.Count];
            collection.CopyTo(arr, index);
            return arr;
        }

        /// <summary>把一个列表组合成为一个字符串，默认逗号分隔</summary>
        /// <param name="value"></param>
        /// <param name="separator">组合分隔符，默认逗号</param>
        /// <returns></returns>
        public static string Join(this IEnumerable value, string separator = ",")
        {
            if (value == null) return null;
            var sb = new StringBuilder();
            foreach (var item in value)
            {
                sb.Separate(separator).Append(item + "");
            }
            return sb.ToString();
        }

        /// <summary>把一个列表组合成为一个字符串，默认逗号分隔</summary>
        /// <param name="value"></param>
        /// <param name="separator">组合分隔符，默认逗号</param>
        /// <param name="func">把对象转为字符串的委托</param>
        /// <returns></returns>
        public static string Join<T>(this IEnumerable<T> value, string separator = ",", Func<T, string> func = null)
        {
            if (value == null) return null;
            var sb = new StringBuilder();
            if (func == null) func = obj => obj + "";
            foreach (var item in value)
            {
                sb.Separate(separator).Append(func(item));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 在考虑依赖关系的情况下，使用托普法进行排序
        /// </summary>
        /// <typeparam name="T">要排序的类型.</typeparam>
        /// <param name="source">要排序的数据</param>
        /// <param name="getDependencies">依赖项查询</param>
        /// <returns></returns>
        public static List<T> SortByDependencies<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> getDependencies)
        {
            var sorted = new List<T>();
            var visited = new Dictionary<T, bool>();

            foreach (var item in source)
            {
                SortByDependenciesVisit(item, getDependencies, sorted, visited);
            }

            return sorted;
        }

        private static void SortByDependenciesVisit<T>(T item, Func<T, IEnumerable<T>> getDependencies, List<T> sorted, Dictionary<T, bool> visited)
        {
            bool inProcess;
            var alreadyVisited = visited.TryGetValue(item, out inProcess);

            if (alreadyVisited)
            {
                if (inProcess)
                {
                    throw new ArgumentException("Cyclic dependency found!");
                }
            }
            else
            {
                visited[item] = true;

                var dependencies = getDependencies(item);
                if (dependencies != null)
                {
                    foreach (var dependency in dependencies)
                    {
                        SortByDependenciesVisit(dependency, getDependencies, sorted, visited);
                    }
                }

                visited[item] = false;
                sorted.Add(item);
            }
        }
    }
}
