@using Microsoft.Extensions.Logging
@inject ILogger<ExceptionModal> Logger

<div class="container container-modal">
    <div class="c-modal">
        <div class="exception-header mb-2">
            <i class="ri-emotion-unhappy-line"></i>
            <span>Ops</span>
        </div>
        <div class="text">
            @if (Exception != null)
            {
                <code>@Message</code>
            }
        </div>
        <div class="button-container">
            <div @onclick="OnRetryClick" class="card-button">
                <span>Riprova</span>
            </div>
            
            <div @onclick="OnContinueClick" class="card-button">
                <span>Continua</span>
            </div>
        </div>
    </div>
</div>

@code {
    [Parameter] public Exception? Exception { get; set; }
    [Parameter] public EventCallback OnRetry { get; set; }
    [Parameter] public ErrorBoundary? ErrorBoundary { get; set; }

    private string Message { get; set; } = "";

    protected override void OnInitialized()
    {
        if (Exception == null) return;

        if (Exception.Message.Contains("Failed to connect to"))
        {
            var ipPort = Exception.Message.Split("to /")[1];

            Message = $"Impossibile collegarsi al server ({ipPort})";
        }
        else
        {
            Message = Exception.Message;
        }

        Logger.LogError(Exception, "Errore nel componente Blazor: {Message}", Message);
        StateHasChanged();
    }

    private async Task OnRetryClick()
    {
        await OnRetry.InvokeAsync();
    }

    private async Task OnContinueClick()
    {
        NavigationManager.NavigateTo("/");
        await OnRetry.InvokeAsync();
    }
}