using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace Valg.EVA.Skanning.UserInterfaceElements
{
    public class FocusedPopup : Popup
    {
        protected override void OnOpened(System.EventArgs e)
        {
            base.OnOpened(e);

            var parentStackPanel = Parent as StackPanel;
            if (parentStackPanel != null && Tag != null)
            {
                Width = parentStackPanel.ActualWidth - HorizontalOffset + 0.5;
            }
            else
            {
                Width = PlacementTarget.DesiredSize.Width + 0.5;
            }

            VerticalOffset = -0.5;

            
            System.Threading.ThreadPool.QueueUserWorkItem(
                x =>
                {
                    System.Threading.Thread.Sleep(100);
                    Dispatcher.Invoke(() =>
                    {
                        MoveFocus(Child);
                    });
                });
        }

        protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
        {
            base.OnLostKeyboardFocus(e);

            if (!IsKeyboardFocusWithin)
            {
                
                
                IsOpen = false;
            }
        }

        protected override void OnKeyUp(KeyEventArgs e)
        {
            base.OnKeyUp(e);

            if (e.Key == Key.Escape)
            {
                IsOpen = false;
                MoveFocus(PlacementTarget);
            }
        }

        private void MoveFocus(UIElement uiElement)
        {
            if (uiElement != null)
                uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }
}
