using System.Windows;

namespace Valg.EVA.Skanning.UserInterfaceElements
{
    public static class FocusExtension
    {
        public static bool? GetIsFocused(DependencyObject dependencyObject)
        {
            return (bool?)dependencyObject.GetValue(IsFocusedProperty);
        }

        
        
        
        public static void SetIsFocused(DependencyObject dependencyObject, bool? isFocused)
        {
            dependencyObject.SetValue(IsFocusedProperty, isFocused);
        }

        public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached("IsFocused", typeof(bool?), typeof(FocusExtension),
            new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsFocusedPropertyChanged));

        private static void OnIsFocusedPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            var uiElement = (FrameworkElement)dependencyObject;
            if (dependencyPropertyChangedEventArgs.OldValue == null)
            {
                HookEvents(uiElement);
            }

            var newValue = (bool?)dependencyPropertyChangedEventArgs.NewValue;
            if (newValue.GetValueOrDefault())
            {
                uiElement.BringIntoView();

                UnhookEvents(uiElement);

                uiElement.Focus();

                HookEvents(uiElement);
            }
        }

        private static void UnhookEvents(FrameworkElement uiElement)
        {
            uiElement.GotFocus -= FrameworkElement_GotFocus;
            uiElement.LostFocus -= FrameworkElement_LostFocus;
        }

        private static void HookEvents(FrameworkElement uiElement)
        {
            uiElement.GotFocus += FrameworkElement_GotFocus;
            uiElement.LostFocus += FrameworkElement_LostFocus;
        }

        
        
        
        private static void FrameworkElement_GotFocus(object sender, RoutedEventArgs e)
        {
            ((FrameworkElement)sender).SetValue(IsFocusedProperty, true);
        }

        
        
        
        private static void FrameworkElement_LostFocus(object sender, RoutedEventArgs e)
        {

            ((FrameworkElement)sender).SetValue(IsFocusedProperty, false);
        }
    }
}

