using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using C1.Silverlight.Extended;
using System.Collections.Generic;
using System.ComponentModel;

namespace GaugeBuilder
{
    public class DependencyObjectEditor<T>
        : ComboBox, ITypeEditorControl
    {
        private PropertyAttribute _selectedProperty;

        #region ITypeEditorControl Members

        public event PropertyChangedEventHandler ValueChanged;

        bool ITypeEditorControl.Supports(PropertyAttribute Property)
        {
            return Property.PropertyInfo.PropertyType == typeof(T);
        }

        public void Attach(PropertyAttribute property)
        {
            _selectedProperty = property;
            this.SelectionChanged += cb_SelectionChanged;

            // set initial value
            this.HorizontalContentAlignment = HorizontalAlignment.Left;
            this.DisplayMemberPath = "Name";

            if (this.SelectedItem == null)
            {
                this.SelectedItem = FindWrapper(property.PropertyInfo.GetValue(property.SelectedObject, null));
            }
        }

        private object FindWrapper(object element)
        {
            foreach (var item in ItemsSource)
            {
                var wrapper = item as Wrapper<T>;
                if (wrapper != null) 
                {
                    if (object.ReferenceEquals(wrapper.Element, element))
                    {
                        return wrapper;
                    }
                }
            }
            return null;
        }

        public void Detach(PropertyAttribute property)
        {
            this.SelectionChanged -= cb_SelectionChanged;
        }

        private void cb_SelectionChanged(object sender, EventArgs e)
        {
            if (this.SelectedIndex > -1)
            {
                var wrapper = (Wrapper<T>) this.Items[SelectedIndex];
                _selectedProperty.PropertyInfo.SetValue(_selectedProperty.SelectedObject, wrapper.Element, null);
            }

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

        ITypeEditorControl ITypeEditorControl.Create()
        {
            return new DependencyObjectEditor<T>() { ItemsSource = ItemsSource };
        }

        #endregion
    }
}
