//==============================================================
//  版权所有：深圳杰文科技
//  文件名：ComboBox.ext.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;

namespace Infrastructure.Components
{
	public static class ComboBoxExt
	{
		public static void AddEnum<TEnum>(this RepositoryItemImageComboBox cmb)
		{
			Type type = typeof(TEnum);
			if (!type.IsEnum)
			{
				throw new Exception(string.Format("{0}不是枚举类型", type.FullName));
			}

			string[] names = Enum.GetNames(type);
			foreach (string name in names)
			{
				int value = (int)Enum.Parse(type, name);
				cmb.Items.Add(new ImageComboBoxItem(name, value, -1));
			}
		}

		public static void AddEnum<TEnum>(this ImageComboBoxEdit cmb)
		{
			Type type = typeof(TEnum);
			if (!type.IsEnum)
			{
				throw new Exception(string.Format("{0}不是枚举类型", type.FullName));
			}

			string[] names = Enum.GetNames(type);
			foreach (string name in names)
			{
				int value = (int)Enum.Parse(type, name);
				cmb.Properties.Items.Add(new ImageComboBoxItem(name, value, -1));
			}
		}

		public static void AddEnum<TEnum>(this ImageComboBoxEdit cmb, string all, int defaultIndex = -1)
		{
			Add(cmb, all, -1);
			AddEnum<TEnum>(cmb);
			cmb.SelectedIndex = defaultIndex;
		}

		public static void Add(this ImageComboBoxEdit cmb, string name, object value)
		{
			cmb.Properties.Items.Add(new ImageComboBoxItem(name, value, -1));
		}

		public static T GetSelectedValue<T>(this ImageComboBoxEdit cmb)
		{
			return GetSelectedValue<T>(cmb, default(T));
		}

		public static T GetSelectedValue<T>(this ImageComboBoxEdit cmb, T defaultValue)
		{
			if (cmb.SelectedIndex < 0)
			{
				return defaultValue;
			}

			ImageComboBoxItem item = cmb.SelectedItem as ImageComboBoxItem;
			if (item == null)
			{
				return default(T);
			}

			return (T)item.Value;
		}
	}
}
