using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using VIZ.Framework.Core;

namespace VIZ.Framework.Common
{
    /// <summary>
    /// 拖拽窗口区域
    /// </summary>
    public class DragWindowBar : Border
    {
        /// <summary>
        /// 鼠标按下的坐标
        /// </summary>
        private Point? mouseLeftButtonDownPoint;

        /// <summary>
        /// 所属窗口
        /// </summary>
        private Window ownerWindow;

        /// <summary>
        /// 获取所属窗口
        /// </summary>
        /// <returns>所属窗口</returns>
        private Window GetOwnerWindow()
        {
            if (this.ownerWindow != null)
                return this.ownerWindow;

            this.ownerWindow = WPFHelper.GetAncestorByType<Window>(this);

            return this.ownerWindow;
        }

        /// <summary>
        /// 鼠标按下
        /// </summary>
        protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseLeftButtonDown(e);

            this.mouseLeftButtonDownPoint = e.GetPosition(this);
        }

        /// <summary>
        /// 鼠标移动
        /// </summary>
        protected override void OnPreviewMouseMove(MouseEventArgs e)
        {
            base.OnPreviewMouseMove(e);

            if (e.LeftButton != MouseButtonState.Pressed || this.mouseLeftButtonDownPoint == null)
                return;

            Point point = e.GetPosition(this);

            if (Math.Abs(point.X - this.mouseLeftButtonDownPoint.Value.X) >= 5 || Math.Abs(point.Y - this.mouseLeftButtonDownPoint.Value.Y) >= 5)
            {
                Window window = this.GetOwnerWindow();
                window.DragMove();
            }
        }

        /// <summary>
        /// 鼠标释放
        /// </summary>
        protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseLeftButtonUp(e);

            this.mouseLeftButtonDownPoint = null;
        }
    }
}
