using JiaZhiQuan.Common.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace JiaZhiQuan.Common.Utils
{
    /// <summary>
    /// 特性工具类
    /// </summary>
    public static class AttributeUtils
    {
        /// <summary>
        /// 获取枚举字段的特性
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T GetEnumDescription<T>(System.Enum value) where T : Attribute
        {
            var type = value.GetType();
            var name = System.Enum.GetName(type, value);
            if (name == null) return null;
            var field = type.GetField(name);
            if (field == null) return null;
            return Attribute.GetCustomAttribute(field, typeof(T)) as T;
        }

        /// <summary>
        /// 获取枚举字段的特性
        /// </summary>
        /// <typeparam name="TEnum">枚举</typeparam>
        /// <typeparam name="TAttribute">特性</typeparam>
        /// <param name="func"></param>
        /// <returns></returns>
        public static List<TAttribute> FindEnumValues<TEnum, TAttribute>(Func<TAttribute, bool> func)
            where TEnum : System.Enum
            where TAttribute : Attribute
        {
            List<TAttribute> attributes = new List<TAttribute>();
            var fields = typeof(TEnum).GetFields(bindingAttr: BindingFlags.Public | BindingFlags.Static);
            fields.ForEach(e =>
            {
                // 获取枚举字段的特性
                var attribute = Attribute.GetCustomAttribute(e, typeof(TAttribute)) as TAttribute;
                if (func(attribute))
                {
                    attributes.Add(attribute);
                }
            });
            return attributes;
        }
    }
}
