using System;
using System.Linq;
using DevExpress.Xpf.Editors;
using System.Windows;
using DevExpress.Xpf.Editors.Themes;
using DevExpress.Xpf.Editors.Helpers;
using DevExpress.Xpf.Core;
using System.Windows.Controls;
using DevExpress.Xpf.Editors.Popups;
using System.Windows.Data;
using DevExpress.Xpf.Editors.Internal;

namespace BeWo.View.Controls
{
	public class EnumComboBoxStyleSettings : BaseComboBoxStyleSettings
	{
		public Type EnumType
		{
			get;
			set;
		}

		public override void ApplyToEdit(BaseEdit editor)
		{
			base.ApplyToEdit(editor);
			var cb = editor as LookUpEditBase;

			cb.ItemsSource = EnumHelper.GetEnumSource(EnumType, false);
			cb.ItemTemplate = (DataTemplate)Application.Current.FindResource("whithAttributeItemTemplate");
			cb.DisplayTextConverter = (IValueConverter)Application.Current.FindResource("enumToDescriptionConverter");
		}

		protected override Style GetItemContainerStyle(LookUpEditBase cb)
		{
			if (HasFlagsAttribute())
				return (Style)cb.FindResource(new EditorListBoxThemeKeyExtension { ResourceKey = EditorListBoxThemeKeys.CheckBoxItemStyle, ThemeName = ThemeHelper.GetEditorThemeName(cb) });
			return (Style)cb.FindResource(new EditorListBoxThemeKeyExtension { ResourceKey = EditorListBoxThemeKeys.DefaultItemStyle, ThemeName = ThemeHelper.GetEditorThemeName(cb) });
		}

		protected override SelectionMode SelectionMode
		{
			get
			{
				return HasFlagsAttribute() ? SelectionMode.Multiple : SelectionMode.Single;
			}
		}

		protected override bool CloseOnMouseUp
		{
			get { return !HasFlagsAttribute(); }
		}

		protected override bool ShowCustomItem(LookUpEditBase editor)
		{
			return HasFlagsAttribute();
		}

		protected override SelectionEventMode GetSelectionEventMode(ISelectorEdit ce)
		{
			if (HasFlagsAttribute())
				return SelectionEventMode.MouseUp;

			return !((LookUpEditBase)ce).AllowItemHighlighting ? SelectionEventMode.MouseDown : SelectionEventMode.MouseEnter;
		}

		public override PopupFooterButtons GetPopupFooterButtons(PopupBaseEdit editor)
		{
			return HasFlagsAttribute() ? PopupFooterButtons.OkCancel : PopupFooterButtons.None;
		}

		bool HasFlagsAttribute()
		{
			var fa = (FlagsAttribute[])EnumType.GetCustomAttributes(typeof(FlagsAttribute), true);
			var c = fa.Count();

			return c != 0;
		}
	}
}
