Option Strict On
Option Explicit On

Imports System.Windows.Forms
Imports SkiaSharp

Namespace Nexamas.UI.Rendering

    Friend NotInheritable Class MASPanelShellDragController

        Private _isDragging As Boolean
        Private _dragOffsetPx As SKPoint
        Private _dragBoundsPx As SKRect

        Friend ReadOnly Property IsDragging As Boolean
            Get
                Return _isDragging
            End Get
        End Property

        Friend Function BeginDrag(pointerPx As SKPoint,
                                  shellResult As MASPanelShellResult,
                                  currentBoundsPx As SKRect,
                                  button As MouseButtons) As Boolean

            If button <> MouseButtons.Left Then Return False
            If shellResult Is Nothing Then Return False
            If currentBoundsPx.IsEmpty Then Return False

            If shellResult.HitTest(pointerPx) <> MASPanelShellHitTarget.Header Then
                Return False
            End If

            _isDragging = True
            _dragBoundsPx = currentBoundsPx
            _dragOffsetPx = New SKPoint(
                pointerPx.X - currentBoundsPx.Left,
                pointerPx.Y - currentBoundsPx.Top)

            Return True
        End Function

        Friend Function DragTo(pointerPx As SKPoint,
                               allowedBoundsPx As SKRect) As SKRect

            If Not _isDragging Then Return _dragBoundsPx

            Dim w As Single = _dragBoundsPx.Width
            Dim h As Single = _dragBoundsPx.Height

            Dim left As Single = pointerPx.X - _dragOffsetPx.X
            Dim top As Single = pointerPx.Y - _dragOffsetPx.Y

            If Not allowedBoundsPx.IsEmpty Then
                left = Math.Max(allowedBoundsPx.Left, Math.Min(left, allowedBoundsPx.Right - w))
                top = Math.Max(allowedBoundsPx.Top, Math.Min(top, allowedBoundsPx.Bottom - h))
            End If

            _dragBoundsPx = New SKRect(left, top, left + w, top + h)
            Return _dragBoundsPx
        End Function

        Friend Sub EndDrag()
            _isDragging = False
        End Sub

        Friend Sub Cancel()
            _isDragging = False
        End Sub

    End Class

End Namespace