using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
using C1.Silverlight;
using C1.Silverlight.Extended;

namespace C1Data_Demo
{
    /// <summary>
    /// Custom editor used by C1PropertyGrid to edit Type values.
    /// </summary>
    public class TypeEditor : C1ComboBox, ITypeEditorControl
    {
        private PropertyAttribute _selectedProperty;
        private DefaultValueConverter _converter;
        public event PropertyChangedEventHandler ValueChanged;

        public TypeEditor()
        {
            _converter = new DefaultValueConverter();
        }

        public TypeEditor(DefaultValueConverter converter)
        {
            _converter = converter;
        }

        public virtual ITypeEditorControl Create()
        {
            TypeEditor editor = new TypeEditor(_converter);
            editor.ValueChanged += new PropertyChangedEventHandler(editor_ValueChanged);
            return editor;
        }

        private void editor_ValueChanged(object sender, PropertyChangedEventArgs e)
        {
             TypeEditor editor = sender as TypeEditor;
             editor._converter.TargetType = editor.SelectedItem as Type;
        }

        public virtual bool Supports(PropertyAttribute Property)
        {
            return (Property.PropertyInfo.PropertyType == typeof(Type));
        }

        public virtual void Attach(PropertyAttribute property)
        {
            _selectedProperty = property;

            // set MultiValue values
            this.ItemsSource = new List<Type>() { typeof(int), typeof(string) };

            // bind editor
            Binding editorBinding = new Binding(property.MemberName);
            editorBinding.Mode = BindingMode.TwoWay;
            editorBinding.Source = property.SelectedObject;

            this.SetBinding(C1ComboBox.SelectedItemProperty, editorBinding);
            if (_selectedProperty.PropertyInfo.GetValue(_selectedProperty.SelectedObject, null) == null)
            {
                this.SelectedIndex = 0;
            }
            // handle value changes
            this.SelectedItemChanged += TypeEditor_SelectedItemChanged;
        }

        public virtual void Detach(PropertyAttribute property)
        {
            this.SelectedItemChanged -= TypeEditor_SelectedItemChanged;
        }

        public DefaultValueConverter GetConverter()
        {
            return _converter;
        }

        private void TypeEditor_SelectedItemChanged(object sender, PropertyChangedEventArgs<object> e)
        {
            OnValueChanged();
        }

        protected void OnValueChanged()
        {
            if (ValueChanged != null)
            {
                ValueChanged(this, new PropertyChangedEventArgs(_selectedProperty.MemberName));
            }
        }
    }
}
