@using System.Diagnostics
@using Moonlight.App.Exceptions
@using Moonlight.App.Models.Enums
@using Moonlight.App.Services

@inherits ErrorBoundaryBase
@inject IdentityService IdentityService

@if (Crashed)
{
    if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development" || IdentityService.Permissions[Permission.AdminViewExceptions]) // TODO: Add check for admin perms to show exceptions to admins
    {
        if (Exception != null)
        {
            <div class="card border border-danger">
                <div class="card-header">
                    <span class="card-title text-danger fw-bold fs-3">An unhandled exception occured</span>
                </div>
                <div class="card-body fw-bold">
                    @(Formatter.FormatLineBreaks(Exception.ToStringDemystified()))
                </div>
            </div>
        }
    }
    else
    {
        <h1>Crashed lol :c</h1>
    }
}
else
{
    if (ErrorMessages.Any())
    {
        foreach (var errorMessage in ErrorMessages)
        {
            <div class="alert alert-danger bg-danger text-white p-3 mb-5 fw-bold">
                @errorMessage
            </div>
        }
    }
    
    @ChildContent
}

@code 
{
    private bool Crashed = false;
    private List<string> ErrorMessages = new();
    private Exception? Exception;

    protected override Task OnErrorAsync(Exception exception)
    {
        if (exception is DisplayException displayException)
        {
            ErrorMessages.Add(displayException.Message);

            Task.Run(async () =>
            {
                await Task.Delay(TimeSpan.FromSeconds(5));
                ErrorMessages.Remove(displayException.Message);
                await InvokeAsync(StateHasChanged);
            });
        }
        else
        {
            Exception = exception;
            Crashed = true;
        }
        
        Recover();
        
        return Task.CompletedTask;
    }
}