Option Strict On
Option Explicit On

Imports System
Imports System.IO
Imports System.Reflection
Imports System.Windows.Forms
Imports Nexamas.UI.Application
Imports Nexamas.UI.Controls
Imports Nexamas.UI.Layout
Imports Nexamas.UI.Output

Friend NotInheritable Class MainForm
    Inherits Form

    Private ReadOnly _application As MASApplication
    Private ReadOnly _window As MASApplicationWindow

    Public Sub New()
        Text = "Nexamas UI Minimal Consumer App"
        Width = 1000
        Height = 700
        StartPosition = FormStartPosition.CenterScreen

        Dim masAssembly As Assembly = Assembly.Load("Nexamas.UI")
        If masAssembly Is Nothing Then Throw New InvalidOperationException("Nexamas UI assembly was not loaded.")

        _application = MASApplication.Create()
        _window = _application.CreateWindow(owner:=Me)

        BuildUi()
    End Sub

    Private Sub BuildUi()
        Dim button As MASButton = MASButton.Create("Click me")
        button.SetSize(MASSize.Default)

        Dim outputStatus As MASLabel = _window.Controls.AddLabel("Output facade not exercised yet.")
        outputStatus.LabelVariant = MASLabelVariant.Body
        outputStatus.TextRole = MASLabelTextRole.Secondary
        outputStatus.MultiLine = True
        outputStatus.WordWrap = True
        outputStatus.WithSize(MASSize.FillWidth)

        Dim catalogButton As MASButton = _window.Controls.AddButton("Read Output catalog")
        Dim visualButton As MASButton = _window.Controls.AddButton("Export visual capture")
        Dim pdfButton As MASButton = _window.Controls.AddButton("Check PDF unsupported")

        AddHandler button.Click,
            Sub(sender As Object, e As EventArgs)
                _window.Services.Toasts.Success("Nexamas UI is working", "Consumer Test")
                _window.Services.Dialogs.Information("Dialog service is working.", "Nexamas UI")
            End Sub

        AddHandler catalogButton.Click,
            Sub(sender As Object, e As EventArgs)
                Dim catalog As MASOutputCapabilityCatalog = _application.Output.GetCapabilityCatalog()
                outputStatus.Text = "Output catalog: " & If(catalog Is Nothing, "unavailable", catalog.Summary)
                _window.Services.Toasts.Success("Output catalog read through MASApplication.Output.", "Output consumer")
            End Sub

        AddHandler visualButton.Click,
            Sub(sender As Object, e As EventArgs)
                Dim filePath As String = Path.Combine(Path.GetTempPath(), "Nexamas.UI.MinimalConsumer.VisualCapture.png")
                Dim result As MASOutputResult = _application.Output.ExportVisualCapturePng(MASOutputTarget.File(filePath), MASOutputOptions.ForVisualCapture("showcase-real-buttons-light-1x"))
                outputStatus.Text = BuildOutputStatusText("Visual capture", result)
                If result.Succeeded Then
                    _window.Services.Toasts.Success("Visual capture exported to " & filePath, "Output consumer")
                Else
                    _window.Services.Toasts.Warning("Visual capture was not exported.", "Output consumer")
                End If
            End Sub

        AddHandler pdfButton.Click,
            Sub(sender As Object, e As EventArgs)
                Dim result As MASOutputResult = _application.Output.Export(New MASOutputRequest(MASOutputArtifactKind.PdfDocument, MASOutputFormat.Pdf, MASOutputTarget.Memory()))
                outputStatus.Text = BuildOutputStatusText("PDF", result)
                If result.Status = MASOutputOperationStatus.Unsupported Then
                    _window.Services.Toasts.Success("PDF is explicitly unsupported, not falsely certified.", "Output consumer")
                Else
                    _window.Services.Toasts.Warning("PDF returned an unexpected status.", "Output consumer")
                End If
            End Sub

        _window.Controls.LayoutPage(
            Sub(page)
                page.Padding(MASLayoutSpacing.Spacious)
                page.Spacing(MASLayoutSpacing.Medium)
                page.FullWidth(button, MASSize.Default)
                page.FullWidth(outputStatus, MASSize.FillWidth)
                page.ActionGroup(Sub(actions As MASApplicationActionGroupLayoutBuilder)
                                     actions.AlignCenter().EqualItemWidth().Add(catalogButton, MASSize.Default).Add(visualButton, MASSize.Default).Add(pdfButton, MASSize.Default)
                                 End Sub)
            End Sub)
    End Sub

    Private Shared Function BuildOutputStatusText(operationName As String,
                                                  result As MASOutputResult) As String
        If result Is Nothing Then Return operationName & ": no result returned."
        Dim payload As String = If(result.ContentByteCount > 0,
                                   result.ContentByteCount.ToString(Globalization.CultureInfo.InvariantCulture) & " bytes",
                                   If(result.Content.Length > 0,
                                      result.Content.Length.ToString(Globalization.CultureInfo.InvariantCulture) & " chars",
                                      If(result.ArtifactPath.Length > 0, result.ArtifactPath, "no payload")))
        Return operationName & ": " & result.Status.ToString() & " | " & payload & " | " & result.Summary
    End Function

    Protected Overrides Sub OnFormClosed(e As FormClosedEventArgs)
        If _window IsNot Nothing Then _window.Dispose()
        If _application IsNot Nothing Then _application.Dispose()
        MyBase.OnFormClosed(e)
    End Sub
End Class

Friend Module Program
    <STAThread>
    Public Sub Main()
        Global.System.Windows.Forms.Application.EnableVisualStyles()
        Global.System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(False)
        Global.System.Windows.Forms.Application.Run(New MainForm())
    End Sub
End Module
