Option Strict On
Option Explicit On

Imports SkiaSharp

Namespace Nexamas.UI.Rendering

    Friend NotInheritable Class MASWarmPaperSurfaceMaterial
        Implements IMASSurfaceMaterial

        Public ReadOnly Property Id As String Implements IMASSurfaceMaterial.Id
            Get
                Return MASSurfaceMaterialIds.WarmPaper
            End Get
        End Property

        Friend Sub Draw(canvas As SKCanvas,
                        context As MASSurfaceMaterialContext) Implements IMASSurfaceMaterial.Draw

            If canvas Is Nothing Then Return
            If context Is Nothing Then Return

            Dim rectPx As SKRect = context.BoundsPx
            Dim radiusPx As Single = context.CornerRadiusPx
            If rectPx.Width <= 0.5F OrElse rectPx.Height <= 0.5F Then Return
            If rectPx.Width <= 0.5F OrElse rectPx.Height <= 0.5F Then Return

            Dim palette As MASSurfaceMaterialPalette =
                MASSurfaceMaterialThemeResolver.Resolve(Me.Id, context)

            Dim rr As SKRoundRect = MASSurfaceMaterialPaintUtils.RoundRect(rectPx, radiusPx)

            Using shader As SKShader = SKShader.CreateLinearGradient(
                    New SKPoint(rectPx.Left, rectPx.Top),
                    New SKPoint(rectPx.Left, rectPx.Bottom),
                    New SKColor() {palette.Top, palette.Mid, palette.Bottom},
                    New Single() {0.0F, 0.55F, 1.0F},
                    SKShaderTileMode.Clamp),
                  p As New SKPaint With {
                    .IsAntialias = True,
                    .IsDither = True,
                    .Style = SKPaintStyle.Fill,
                    .Shader = shader
                  }

                canvas.DrawRoundRect(rr, p)
            End Using

            canvas.Save()
            Try
                canvas.ClipRoundRect(rr, SKClipOperation.Intersect, True)

                Using grain As New SKPaint With {
                    .IsAntialias = True,
                    .IsDither = True,
                    .Style = SKPaintStyle.Stroke,
                    .StrokeWidth = Math.Max(1.0F, context.Dpi),
                    .StrokeCap = SKStrokeCap.Round,
                    .Color = palette.Line
                }
                    Dim y As Single = rectPx.Top + 7.0F * context.Dpi
                    Dim stepPx As Single = Math.Max(9.0F * context.Dpi, rectPx.Height / 18.0F)

                    While y < rectPx.Bottom
                        canvas.DrawLine(
                            rectPx.Left + 12.0F * context.Dpi,
                            y,
                            rectPx.Right - 12.0F * context.Dpi,
                            y + 0.8F * context.Dpi,
                            grain)

                        y += stepPx
                    End While
                End Using

            Finally
                canvas.Restore()
            End Try
        End Sub

    End Class

End Namespace