using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace ReflectionIT.Phone.Behaviors {

    public class EnumDataStateBehavior : Behavior<Control> {

        public bool UseTransitions { get; set; }
        private object StateValue { get; set; }

        public EnumDataStateBehavior() {
            UseTransitions = true;
        }

        protected override void OnAttached() {
            base.OnAttached();
            // postpone UpdateVisualState to the Loaded event to allow it to get initialized
            this.AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
        }

        protected override void OnDetaching() {
            base.OnDetaching();
            this.AssociatedObject.Loaded -= new RoutedEventHandler(AssociatedObject_Loaded);
        }

        private void AssociatedObject_Loaded(object sender, RoutedEventArgs e) {
            UpdateVisualState();
        }

        private void UpdateVisualState() {
            if (this.AssociatedObject != null && StateValue != null) {
                VisualStateManager.GoToState(this.AssociatedObject, StateValue.ToString(), this.UseTransitions);
            }
        }

        #region Binding Dependency Property

        /// <summary> 
        /// Get or Sets the Binding dependency property.  
        /// </summary> 
        [CustomPropertyValueEditor(CustomPropertyValueEditor.PropertyBinding)]
        public object Binding {
            get { return (int)GetValue(BindingProperty); }
            set { SetValue(BindingProperty, value); }
        }

        /// <summary> 
        /// Identifies the Binding dependency property. This enables animation, styling, binding, etc...
        /// </summary> 
        public static readonly DependencyProperty BindingProperty =
            DependencyProperty.Register("Binding",
                                        typeof(object),
                                        typeof(EnumDataStateBehavior),
                                        new PropertyMetadata(null, OnBindingPropertyChanged));

        /// <summary>
        /// Binding changed handler. 
        /// </summary>
        /// <param name="d">EnumDataStateBehavior that changed its Binding.</param>
        /// <param name="e">DependencyPropertyChangedEventArgs.</param> 
        private static void OnBindingPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
            var source = d as EnumDataStateBehavior;
            if (source != null) {
                source.StateValue = (object)e.NewValue;
                source.UpdateVisualState();
            }
        }

        #endregion Binding Dependency Property

    }
}