Option Strict On
Option Explicit On

Imports System
Imports Nexamas.UI.TextInput
Imports SkiaSharp

Namespace Nexamas.UI.TextInput

    ''' <summary>
    ''' Owns the mutable SKPaint clone used by text-input render, hit-test, and caret paths.
    ''' </summary>
    ''' <remarks>
    ''' DPI-01 contract: MASTypography may create short-lived public clones, but a text input
    ''' must not allocate an undisposed native SKPaint clone on every render, hit-test, or
    ''' caret blink. This cache keeps one control-owned mutable clone, replaces it only when
    ''' the effective paint signature changes, and disposes the previous clone deterministically.
    ''' </remarks>
    Friend NotInheritable Class MASTextInputOwnedPaintCache
        Implements IDisposable

        Private _paint As SKPaint
        Private _signature As String = String.Empty
        Private _disposed As Boolean

        Friend Function AdoptOrReuse(candidate As SKPaint) As SKPaint
            If candidate Is Nothing Then Return Nothing
            ThrowIfDisposed()

            Dim candidateSignature As String = MASTextInputLayoutSnapshotBuilder.CreatePaintSignature(candidate)

            If _paint Is Nothing OrElse Not String.Equals(_signature, candidateSignature, StringComparison.Ordinal) Then
                ReplaceOwnedPaint(candidate, candidateSignature)
            End If

            Return _paint
        End Function

        Friend ReadOnly Property ActivePaintCountForProof As Integer
            Get
                If _paint Is Nothing Then Return 0
                Return 1
            End Get
        End Property

        Friend ReadOnly Property SignatureForProof As String
            Get
                Return _signature
            End Get
        End Property

        Private Sub ReplaceOwnedPaint(candidate As SKPaint,
                                      candidateSignature As String)
            DisposeOwnedPaint()
            _paint = candidate.Clone()
            _signature = If(candidateSignature, String.Empty)
        End Sub

        Private Sub DisposeOwnedPaint()
            Dim oldPaint As SKPaint = _paint
            _paint = Nothing
            _signature = String.Empty

            If oldPaint Is Nothing Then Return

            Try
                oldPaint.Dispose()
            Catch masCaughtException1 As Exception
                Nexamas.UI.Diagnostics.MASExceptionSilencer.SwallowTextShapingFallback(masCaughtException1)
            End Try
        End Sub

        Private Sub ThrowIfDisposed()
            If _disposed Then Throw New ObjectDisposedException(NameOf(MASTextInputOwnedPaintCache))
        End Sub

        Public Sub Dispose() Implements IDisposable.Dispose
            If _disposed Then Return
            _disposed = True
            DisposeOwnedPaint()
        End Sub

    End Class

End Namespace
