using System.Windows;
using System.Windows.Input;

namespace Common.Behaviors
{
    public static class WindowDragBehavior
    {
        public static readonly DependencyProperty EnableWindowDragProperty =
            DependencyProperty.RegisterAttached(
                "EnableWindowDrag",
                typeof(bool),
                typeof(WindowDragBehavior),
                new PropertyMetadata(false, OnEnableWindowDragChanged));

        public static bool GetEnableWindowDrag(DependencyObject obj) =>
            (bool)obj.GetValue(EnableWindowDragProperty);

        public static void SetEnableWindowDrag(DependencyObject obj, bool value) =>
            obj.SetValue(EnableWindowDragProperty, value);

        private static void OnEnableWindowDragChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is FrameworkElement element)
            {
                if ((bool)e.NewValue)
                    element.MouseLeftButtonDown += Element_MouseLeftButtonDown;
                else
                    element.MouseLeftButtonDown -= Element_MouseLeftButtonDown;
            }
        }

        private static void Element_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (sender is FrameworkElement element)
            {
                var window = Window.GetWindow(element);
                window?.DragMove();
            }
        }
    }
}
