Option Strict On
Option Explicit On

Imports System
Imports Nexamas.UI.TextRendering
Imports SkiaSharp

Namespace Nexamas.UI.TextInput

    ' CONTRACT:
    ' MASTextCompositionRenderer draws IME pre-edit text when the host integrates
    ' platform IME events in Stage 4B.
    '
    ' It must not mutate MASTextInputState, MASTextCompositionState, controller, or scroll.
    Friend NotInheritable Class MASTextCompositionRenderer

        Private Const UNDERLINE_OFFSET_PX As Single = 2.0F
        Private Const UNDERLINE_HEIGHT_PX As Single = 1.0F

        Friend Sub Render(canvas As SKCanvas,
                          snapshot As MASTextInputLayoutSnapshot,
                          composition As MASTextCompositionState)

            If canvas Is Nothing Then Return
            If snapshot Is Nothing Then Return
            If composition Is Nothing OrElse Not composition.IsActive Then Return
            If String.IsNullOrEmpty(composition.Text) Then Return
            If snapshot.Paint Is Nothing Then Return
            If snapshot.InlineLayout Is Nothing Then Return

            Dim x As Single = snapshot.InlineLayout.GetCaretX(snapshot.CaretIndex)
            Dim baselineY As Single = snapshot.BaselineY
            If snapshot.CrispRendering Then
                x = MASTextCrispRendering.SnapTextX(x)
                baselineY = MASTextCrispRendering.SnapBaseline(baselineY)
            End If

            MASShapedText.Draw(
                canvas:=canvas,
                text:=composition.Text,
                x:=x,
                baselineY:=baselineY,
                paint:=snapshot.Paint
            )

            Dim width As Single = Math.Max(0.0F, MASShapedText.MeasureWidth(composition.Text, snapshot.Paint))
            If width <= 0.0F Then Return

            Dim y As Single = Math.Min(snapshot.ContentRect.Bottom - 1.0F,
                                       baselineY + UNDERLINE_OFFSET_PX)

            Using p As New SKPaint With {
                .IsAntialias = False,
                .Style = SKPaintStyle.Fill,
                .Color = snapshot.Paint.Color.WithAlpha(180)
            }
                canvas.DrawRect(New SKRect(x, y, x + width, y + UNDERLINE_HEIGHT_PX), p)
            End Using
        End Sub

    End Class

End Namespace
