@using AliasDb
@using Microsoft.EntityFrameworkCore
@using Microsoft.EntityFrameworkCore.Metadata.Internal
@inherits AuthorizePageBase
@inject AliasDbContext dbContext
@page "/"

<PageTitle>Aliaseses</PageTitle>

<div class="row align-items-center">
    <div class="col">
        <h1>Aliaseses</h1>
    </div>
    <div class="col-auto">
        <a href="/add-alias" class="btn btn-success">
            <span class="bi bi-file-earmark-plus" aria-hidden="true"></span> + Add new alias
        </a>
    </div>
</div>
<p>Find all of your aliases below.</p>

@if (IsLoading)
{
    <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">Loading...</span>
    </div>
}
else
{
    <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 g-4">
        @foreach (var alias in Aliases)
        {
            <Alias Login="@alias"/>
        }
    </div>
}

@code {
    private bool IsLoading { get; set; } = true;
    private List<Login> Aliases { get; set; } = new List<Login>();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await LoadAliasesAsync();
        }
    }

    private async Task LoadAliasesAsync()
    {
        IsLoading = true;
        StateHasChanged();

        // Load the aliases from the database.
        var user = UserService.User();
        Aliases = await dbContext.Logins
            .Include(x => x.Identity)
            .Include(x => x.Service)
            .Include(x => x.Passwords)
            .Where(x => x.UserId == user.Id)
            .ToListAsync();

        IsLoading = false;
        StateHasChanged();
    }
}
