@using Radzen
@using System.Text.Json
@inject IJSRuntime JSRuntime
<RadzenCard Variant="Variant.Outlined" class="rz-mt-4">
    <RadzenStack Orientation="Orientation.Vertical" Gap="0.5rem" @attributes=@Attributes>
        <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center" JustifyContent="JustifyContent.SpaceBetween">
            <RadzenText TextStyle="TextStyle.Subtitle1" TagName="TagName.P" class="rz-m-0">Console log</RadzenText>
            <RadzenButton Click=@OnClearClick Text="Clear console" ButtonStyle="ButtonStyle.Base" Variant="Variant.Flat" Size="ButtonSize.Small" />
        </RadzenStack>
        <RadzenStack Orientation="Orientation.Vertical" Gap="0" ID="event-console" class="rz-pt-1" Style="border-top: var(--rz-grid-cell-border); min-height: 2rem; max-height: 12rem; overflow: auto;">
            @foreach (var message in messages)
            {
                <RadzenAlert ShowIcon="false" Variant="Variant.Flat" AlertStyle="message.AlertStyle" Size="AlertSize.ExtraSmall" Shade="Shade.Lighter" AllowClose="false" Style="font-size: 0.75rem">
                    <span Style="opacity: 0.6;">@message.Date.ToString("HH:mm:ss.ff")</span> @message.Text
                </RadzenAlert>
            }
        </RadzenStack>
    </RadzenStack>
</RadzenCard>

@code {
    class Message
    {
        public DateTime Date { get; set; }
        public string Text { get; set; }
        public AlertStyle AlertStyle { get; set; }
    }

    [Parameter(CaptureUnmatchedValues = true)]
    public IDictionary<string, object> Attributes { get; set; }
    IList<Message> messages = new List<Message>();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender)
        {
            await JSRuntime.InvokeVoidAsync("scrollToBottom", "event-console");
        }
    }

    void OnClearClick()
    {
        Clear();
    }

    public void Clear()
    {
        messages.Clear();

        InvokeAsync(StateHasChanged);
    }

    public void Log(string message, AlertStyle alertStyle = AlertStyle.Info)
    {
        messages.Add(new Message { Date = DateTime.Now, Text = message, AlertStyle = alertStyle });

        InvokeAsync(StateHasChanged);
    }

    public void Log(object value)
    {
        Log(JsonSerializer.Serialize(value));
    }
}