@page "/options/sessions"
@using Microsoft.EntityFrameworkCore
@using songrequests_blazor.Data
@inject Microsoft.EntityFrameworkCore.IDbContextFactory<LocalDbContext> DataContextFactory
<h3>Sessions</h3>

<a class="btn btn-primary mb-3" href="/options/sessions/edit">Session anlegen</a>

<ul class="list-group">
    @foreach (var itm in Items ?? [])
    {
        <li class="list-group-item d-flex justify-content-between align-items-center">
            Erstellt am @itm.Created
            <div>
                <a class="btn btn-primary" href="/options/libraries/edit/@itm.Id">Bearbeiten</a>
                <button type="button" class="btn btn-secondary" @onclick="args => ShowDialog(itm)">Entfernen</button>
            </div>
        </li>
    }
</ul>

<ModalComponent @ref="modal">
    <Title>Löschen bestätigen</Title>
    <Body>
        Willst du die Session wirklich löschen?
    </Body>
    <Footer>
        <button class="btn btn-danger" @onclick="RemoveItem">Ja</button>
        <button class="btn btn-primary" @onclick="CloseDialog">Nein</button>
    </Footer>
</ModalComponent>

@code {

    List<Session>? Items { get; set; }

    private ModalComponent modal = null!;
    Session? ModalItem { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await ShowList();
    }

    private async Task ShowList()
    {
        using (LocalDbContext db = await DataContextFactory.CreateDbContextAsync())
        {
            Items = await db.Sessions.OrderBy(l => l.Created).ToListAsync();
        }
    }

    private async Task ShowDialog(Session itm)
    {
        ModalItem = itm;
        await modal.ShowAsync();
    }
    private async Task CloseDialog()
    {
        ModalItem = null;
        await modal.CloseAsync();
    }

    private async Task RemoveItem()
    {
        if (ModalItem == null) return;
        using (LocalDbContext db = await DataContextFactory.CreateDbContextAsync())
        {
            db.Sessions.Remove(ModalItem);
            await db.SaveChangesAsync();
            await ShowList();
        }
        await CloseDialog();
    }
}