using System;
using System.Windows.Input;
using System.Windows.Threading;
using Valg.EVA.Skanning.UserInterfaceElements.Help;

namespace Valg.EVA.Skanning.Verify.Startup.VerifyBallotPaper.BallotNumber
{
    public partial class BallotNumberView : IHelpContributor
    {
        public BallotNumberView()
        {
            InitializeComponent();
            AffiliateDropDown.PreviewKeyDown += StopAndReRouteEventToUserControl;
        }

        private void StopAndReRouteEventToUserControl(object sender, KeyEventArgs sourceEvent)
        {
            if (!sourceEvent.Key.Equals(Key.Left) && (!sourceEvent.Key.Equals(Key.Right)))
                return;

            sourceEvent.Handled = true;
            var relaunchedEvent = CreateNewKeyDownEventArgs(sourceEvent);
            RaiseEvent(relaunchedEvent);
        }

        private KeyEventArgs CreateNewKeyDownEventArgs(KeyEventArgs sourceEvent)
        {
            return new KeyEventArgs(
                sourceEvent.KeyboardDevice,
                sourceEvent.InputSource,
                sourceEvent.Timestamp,
                sourceEvent.Key)
            {
                RoutedEvent = Keyboard.KeyDownEvent,
                Source = sourceEvent.OriginalSource
            };
        }

        private void AffiliateDropDown_OnDropDownClosed(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(SetFocusOnContinueButtonAfterAffiliationSelection));
        }

        private void SetFocusOnContinueButtonAfterAffiliationSelection()
        {
            var ballotNumberViewModel = DataContext as BallotNumberViewModel;
            if (ballotNumberViewModel != null)
            {
                if (!ballotNumberViewModel.CheckForCorrectionsVisible)
                {
                    NextButtonBlinking.Focus();
                }
            }
        }

        public string HelpContributionId { get { return HelpContributionIds.Seddelnummer; } }
    }
}

