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

namespace Valg.EVA.Skanning.Verify.Startup.VerifyBallotPaper.RenumberStrikeout
{
    public class FocusedRenumberValuesPopup : Popup
    {
        protected override void OnOpened(System.EventArgs e)
        {
            base.OnOpened(e);

            ((RenumberStrikeoutContextMenuViewModel)DataContext).CurrentUIElement = (UIElement)Parent;

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

            
            System.Threading.ThreadPool.QueueUserWorkItem(
                x =>
                {
                    System.Threading.Thread.Sleep(100);
                    Dispatcher.Invoke(() =>
                    {
                        var listBox = FindName("RenumberValuesListBox");
                        var box = (ListBox)listBox;
                        if (box != null)
                        {
                            MoveFocus((UIElement)listBox);
                            box.SelectedIndex = 0;
                        }
                        
                    });
                });
        }
        
        private void MoveFocus(UIElement uiElement)
        {
            if (uiElement != null)
                uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }
}
