using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace VIZ.TVP.FTB.Module
{ /// <summary>
  /// 枚举辅助类
  /// </summary>
    public static class EnumHelper
    {

        /// <summary>
        /// 获取枚举描述信息
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <returns>配置值</returns>
        public static string GetDescriptionCBA(this Enum value)
        {
            if (value == null)
                return string.Empty;

            FieldInfo field = value.GetType().GetField(value.ToString());
            if (field == null)
                return string.Empty;

            DescriptionAttribute attribute = field.GetCustomAttribute<DescriptionAttribute>(false);

            if (attribute == null)
                return string.Empty;

            return attribute.Description;
        }

        /// <summary>
        /// 获取枚举的枚举模型
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <returns>枚举模型列表</returns>
        public static List<EnumModel> GetEnumModels<TEnum>()
        {
            Type type = typeof(TEnum);
            return GetEnumModels(type);
        }

        /// <summary>
        /// 获取枚举的枚举模型
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <returns>枚举模型列表</returns>
        public static List<EnumModel> GetEnumModels(Type type)
        {
            if (!type.IsEnum)
                throw new Exception($"type: {type.Name} is not enum.");

            List<EnumModel> models = new List<EnumModel>();

            Array names = Enum.GetNames(type);

            foreach (object name in names)
            {
                if (name == null)
                    continue;

                FieldInfo field = type.GetField(name.ToString());
                if (field == null)
                    continue;

                DescriptionAttribute attribute = field.GetCustomAttribute<DescriptionAttribute>(false);

                if (attribute == null)
                    continue;

                EnumModel model = new EnumModel();
                model.Key = Enum.Parse(type, name.ToString());
                model.Description = attribute.Description;

                models.Add(model);
            }

            return models;
        }
    }
}
