using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows.Controls;
using ItemsControl=System.Windows.Controls.ItemsControl;

namespace ForeignKeyForSilverlight
{
	[TemplatePart(Name = "PART_EditorControl", Type = typeof(ComboBox))]
	public class CustomComboBoxEditor : GridViewCellEditor
	{
        public CustomComboBoxEditor()
        {
            this.DefaultStyleKey = typeof(CustomComboBoxEditor);
        }

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			RadComboBox comboBoxEditor = (RadComboBox) this.EditorElement;
		    comboBoxEditor.IsEnabled = true;
            comboBoxEditor.SelectionChanged += this.comboBoxEditor_SelectionChanged;

            PropertyInfo[] properties = typeof(GridViewCellEditor).GetProperties(BindingFlags.Instance | BindingFlags.Public);
			object editorSettings = (from property in properties
			                         where property.Name == "EditorSettings"
			                         select property).First().GetValue(this, null);

		    Binding bindingDisplayMemberPath = new Binding();
			bindingDisplayMemberPath.Mode = BindingMode.OneWay;
            bindingDisplayMemberPath.Source = ((CustomComboBoxEditorSettings) editorSettings).DisplayMemberPath;
			comboBoxEditor.SetBinding(ItemsControl.DisplayMemberPathProperty, bindingDisplayMemberPath);

            Binding bindingItemsSource = new Binding();
			bindingItemsSource.Mode = BindingMode.OneWay;
			bindingItemsSource.Source = ((CustomComboBoxEditorSettings) editorSettings).ItemsSource;
			comboBoxEditor.SetBinding(ItemsControl.ItemsSourceProperty, bindingItemsSource);

            comboBoxEditor.GotFocus += this.comboBoxEditor_GotFocus;
		}

        void comboBoxEditor_GotFocus(object sender, RoutedEventArgs e)
        {
            var person = DataContext as Person;
            RadComboBox comboBoxEditor = (RadComboBox) sender;
            if (person != null && person.PersonType != null)
            {
                comboBoxEditor.SelectedItem = (from PersonType item in comboBoxEditor.Items
                                               where item.PersonTypeID == person.PersonType.PersonTypeID
                                               select item).FirstOrDefault();
            }
        }

        void comboBoxEditor_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangedEventArgs e)
        {
            RadComboBox comboBox = sender as RadComboBox;
            if (comboBox != null)
            {
                this.Value = comboBox.SelectedValue;
            }
        }
	}
}