using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using C1.Silverlight.DataGrid;

namespace C1DataGrid_Demo2010
{
    public class C1CommitOnLostFocusBehavior : DependencyObject
    {
        #region ** fields

        #endregion

        #region ** initialization

        /// <summary>
        /// Initializes a new instance of the <see cref="C1CommitOnLostFocusBehavior"/> class.
        /// </summary>
        public C1CommitOnLostFocusBehavior()
        {
        }

        private C1DataGrid AssociatedObject { get; set; }

        private void OnAttached()
        {
            AssociatedObject.LostFocus += new RoutedEventHandler(AssociatedObject_LostFocus);
        }

        private void OnDetaching()
        {
            AssociatedObject.LostFocus -= new RoutedEventHandler(AssociatedObject_LostFocus);
        }

        #endregion

        #region ** object model

        /// <summary>
        /// Gets the commit on lost focus behavior.
        /// </summary>
        /// <param name="obj">The data grid to which the commit is applied.</param>
        /// <returns></returns>
        public static C1CommitOnLostFocusBehavior GetCommitOnLostFocusBehavior(C1DataGrid obj)
        {
            return (C1CommitOnLostFocusBehavior)obj.GetValue(CommitOnLostFocusBehaviorProperty);
        }

        /// <summary>
        /// Sets the commit on lost focus behavior.
        /// </summary>
        /// <param name="obj">The data grid to which the commit will be applied.</param>
        /// <param name="value">The behavior.</param>
        public static void SetCommitOnLostFocusBehavior(C1DataGrid obj, C1CommitOnLostFocusBehavior value)
        {
            obj.SetValue(CommitOnLostFocusBehaviorProperty, value);
        }

        /// <summary>
        /// Attached commit on lost focus behavior.
        /// </summary>
        public static readonly DependencyProperty CommitOnLostFocusBehaviorProperty =
            DependencyProperty.RegisterAttached("CommitOnLostFocusBehavior", typeof(C1CommitOnLostFocusBehavior), typeof(C1CommitOnLostFocusBehavior), new PropertyMetadata(null, new PropertyChangedCallback((d, a) =>
                {
                    if (a.OldValue != null)
                    {
                        var behavior = (C1CommitOnLostFocusBehavior)a.OldValue;
                        behavior.OnDetaching();
                        behavior.AssociatedObject = d as C1DataGrid;
                    }
                    if (a.NewValue != null)
                    {
                        var behavior = (C1CommitOnLostFocusBehavior)a.NewValue;
                        behavior.AssociatedObject = d as C1DataGrid;
                        behavior.OnAttached();
                    }
                })));

        #endregion

        #region ** private stuff

        void AssociatedObject_LostFocus(object sender, RoutedEventArgs e)
        {
            var focusedElement = FocusManager.GetFocusedElement() as FrameworkElement;
            if ((focusedElement == null || !GetAllParents(focusedElement).Contains(AssociatedObject)))
            {
                //Commit changes
                AssociatedObject.EndEditRow(true);
            }
        }

        public static IEnumerable<FrameworkElement> GetAllParents(FrameworkElement elem)
        {
            if (elem == null)
            {
                yield break;
            }
            else
            {
                yield return elem;
            }

            FrameworkElement current = elem;
            while ((current = GetParent(current)) != null)
            {
                yield return current;
            }
        }

        private static FrameworkElement GetParent(FrameworkElement current)
        {
            var parent = VisualTreeHelper.GetParent(current) as FrameworkElement;
            if (parent == null)
            {
                parent = current.Parent as FrameworkElement;
            }
            return parent;
        }

        #endregion
    }
}
