@using Microsoft.CodeAnalysis

@implements IAsyncDisposable

@inject ConsoleHubClient consoleHub
@inject IJSRuntime JS

<div class="w-100 h-100 position-relative overflow-hidden">
    <div @ref="ScrollViewDiv" class="w-100 h-100 position-absolute overflow-x-hidden overflow-y-scroll">
        <div class="ms-2" >
            @foreach(var console in Consoles)
            {
                <ConsoleItem Model="console" />
            }
        </div>
    </div>
</div>

@code {
    private ElementReference ScrollViewDiv;
    private List<ConsoleItemModel> Consoles = [];

    public void AddInfo(string message) => AddMessage(DiagnosticSeverity.Info, message);
    public void AddWarning(string message) => AddMessage(DiagnosticSeverity.Warning, message);
    public void AddError(string message) => AddMessage(DiagnosticSeverity.Error, message);

    public async void AddMessage(DiagnosticSeverity severity, string message)
    {
        if (Consoles.Any() && Consoles[^1].Severity == severity)
        {
            Consoles[^1].Append(message);
        }
        else
        {
            Consoles.Add(new ConsoleItemModel(severity, message));
            StateHasChanged();
        }

        // Đợi UI cập nhật xong rồi scroll
        await Task.Yield();
        await JS.InvokeVoidAsync("ScrollToBottom", ScrollViewDiv);
    }

    public void Clear()
    {
        Consoles.Clear();
        StateHasChanged();
    }


    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        consoleHub.MessageInfo += AddInfo;
        consoleHub.MessageWarning += AddWarning;
        consoleHub.MessageError += AddError;
        await consoleHub.StartAsync();
        await consoleHub.RegisterAllConsoles();
    }

    public async ValueTask DisposeAsync()
    {
        consoleHub.MessageInfo -= AddInfo;
        consoleHub.MessageWarning -= AddWarning;
        consoleHub.MessageError -= AddError;
        await consoleHub.UnregisterAllConsoles();
        await consoleHub.StopAsync();
    }
}
