Option Strict On
Option Explicit On

Imports System
Imports SkiaSharp

Namespace Nexamas.UI.TextInput

    Friend NotInheritable Class MASTextScrollEngine

#Region "Fields"

        Private _offsetPx As Single

#End Region

#Region "Properties"

        Friend Property OffsetPx As Single
            Get
                Return _offsetPx
            End Get
            Set(value As Single)
                _offsetPx = Normalize(value)
            End Set
        End Property

#End Region

#Region "Public API"

        Friend Sub Reset()
            _offsetPx = 0.0F
        End Sub

        Friend Function EnsureCaretVisible(layoutEngine As MASTextInputLayoutEngine,
                                           contentR As SKRect,
                                           paint As SKPaint,
                                           caretIndex As Integer,
                                           isRtl As Boolean,
                                           displayText As String,
                                           Optional crispRendering As Boolean = True) As Boolean

            If layoutEngine Is Nothing Then Return False

            Dim before As Single = _offsetPx

            _offsetPx =
                layoutEngine.EnsureCaretVisible(
                    contentR:=contentR,
                    paint:=paint,
                    currentScrollOffsetPx:=_offsetPx,
                    caretIndex:=caretIndex,
                    isRtl:=isRtl,
                    displayText:=displayText,
                    crispRendering:=crispRendering
                )

            _offsetPx = Normalize(_offsetPx)

            Return Math.Abs(before - _offsetPx) >= 0.01F
        End Function

        Friend Function EnsureInRange(layoutEngine As MASTextInputLayoutEngine,
                                      contentR As SKRect,
                                      paint As SKPaint,
                                      isRtl As Boolean,
                                      displayText As String) As Boolean

            If layoutEngine Is Nothing Then Return False

            Dim before As Single = _offsetPx

            _offsetPx =
                layoutEngine.EnsureScrollInRange(
                    contentR:=contentR,
                    paint:=paint,
                    currentScrollOffsetPx:=_offsetPx,
                    isRtl:=isRtl,
                    displayText:=displayText
                )

            _offsetPx = Normalize(_offsetPx)

            Return Math.Abs(before - _offsetPx) >= 0.01F
        End Function

#End Region

#Region "Helpers"

        Private Shared Function Normalize(value As Single) As Single
            If Single.IsNaN(value) OrElse Single.IsInfinity(value) Then Return 0.0F
            If Math.Abs(value) < 0.01F Then Return 0.0F
            Return value
        End Function

#End Region

    End Class

End Namespace