﻿using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace OGDC.Silverlight.Toolkit.Behaviors
{
    /// <summary>
    /// Behavior pour gérer la perte de Focus
    /// </summary>
    public class FocusHandlerBehaviors : Behavior<FrameworkElement>
    {
        public static readonly DependencyProperty CommandPropertyGF = DependencyProperty.Register("CommandGotFocus", typeof(ICommand), typeof(FocusHandlerBehaviors), null);
        public static readonly DependencyProperty CommandPropertyLF = DependencyProperty.Register("CommandLostFocus", typeof(ICommand), typeof(FocusHandlerBehaviors), null);

        public ICommand CommandGotFocus
        {
            get { return (ICommand)GetValue(CommandPropertyGF); }
            set { SetValue(CommandPropertyGF, value); }
        }

        public ICommand CommandLostFocus
        {
            get { return (ICommand)GetValue(CommandPropertyLF); }
            set { SetValue(CommandPropertyLF, value); }
        }

        /// <summary>
        /// Executé lorsque le behavior est attaché.
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.GotFocus += InvokeGF;
            this.AssociatedObject.LostFocus += InvokeLF;

        }

        /// <summary>
        /// Executé lorsque le behavior est détaché.
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.GotFocus -= InvokeGF;
            this.AssociatedObject.LostFocus -= InvokeLF;
        }

        protected void InvokeGF(object sender, RoutedEventArgs e)
        {
            if (CommandGotFocus != null && CommandGotFocus.CanExecute(null))
                CommandGotFocus.Execute(null);
        }

        protected void InvokeLF(object sender, RoutedEventArgs e)
        {
            if (CommandLostFocus != null && CommandLostFocus.CanExecute(null))
                CommandLostFocus.Execute(null);
        }
    }
}
