using DeviceRepair.Models.Attr;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace DeviceRepair.Utils
{
    public static class EnumExtend
    {

        public static string[] GetComboBoxItems(Type enumType)
        {
            List<string> Captions = new List<string>();

            /* 非枚举对象,返回空数组对象 */
            if (!enumType.IsEnum)
            {
                return Captions.ToArray();
            }

            // 获取枚举的所有字段
            FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
            foreach (FieldInfo field in fields)
            {
                // 获取字段上的所有特性
                object[] attributes = field.GetCustomAttributes(typeof(ComboBoxItemAttribute), false);

                foreach (ComboBoxItemAttribute attribute in attributes)
                {
                    if (!attribute.IsIgnore && !attribute.Caption.IsNull())
                    {
                        Captions.Add(attribute.Caption);
                    }
                }
            }

            return Captions.ToArray();
        }

        public static object GetComboBoxItemValue(Type enumType, string Caption)
        {
            /* 非枚举对象,返回空数组对象 */
            if (!enumType.IsEnum)
            {
                return null;
            }

            // 获取枚举的所有字段

            FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
            foreach (FieldInfo field in fields)
            {
                // 获取字段上的所有特性
                object[] attributes = field.GetCustomAttributes(typeof(ComboBoxItemAttribute), false);

                foreach (ComboBoxItemAttribute attribute in attributes)
                {
                    if (attribute.Caption == Caption)
                    {
                        return Enum.Parse(enumType, field.Name);
                    }
                }
            }
            return null;
        }
    }
}
