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

namespace GaugeBuilder
{
    public partial class PointEditor
        : UserControl, ITypeEditorControl
    {
        private PropertyAttribute _selectedProperty;

        public PointEditor()
        {
            InitializeComponent();
        }

        #region ITypeEditorControl Members

        public event PropertyChangedEventHandler ValueChanged;

        public ITypeEditorControl Create()
        {
            return new PointEditor();
        }

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

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

            // set initial value
            Point controlDefaultValue = (Point)property.PropertyInfo.GetValue(property.SelectedObject, null);
            numX.Value = controlDefaultValue.X; 
            numY.Value = controlDefaultValue.Y;

            numX.ValueChanged += OnValueChanged;
            numY.ValueChanged += OnValueChanged;
        }

        public void Detach(PropertyAttribute property)
        {
            numX.ValueChanged -= OnValueChanged;
            numY.ValueChanged -= OnValueChanged;
        }

        private void OnValueChanged(object sender, EventArgs e) 
        {
            var newValue = new Point(numX.Value, numY.Value);
            _selectedProperty.PropertyInfo.SetValue(_selectedProperty.SelectedObject, newValue, null);

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

        #endregion
    }
}
