@page "/settings/quizzes"
@using FWLAZ_Web.Data
@using Microsoft.EntityFrameworkCore
@inject IDbContextFactory<LocalDbContext> DbFactory ;

<h3>Quizzes</h3>

<a class="btn btn-primary mb-3" href="/settings/quizzes/edit">Neues Quiz</a>

<div class="table-responsive">
    <table class="table table-striped table-hover table-bordered">
        <tbody>
            @foreach (Quiz q in QuizList)
            {
                <tr>
                    <td style="vertical-align:middle;">@q.Name</td>
                    <td style="text-align:right; vertical-align:middle;">
                        <a class="btn btn-primary" href="/settings/quizzes/questions/@q.Id">Fragen</a>
                        <a class="btn btn-primary" href="/settings/quizzes/edit/@q.Id">Bearbeiten</a>
                        <button name="submit" type="submit" class="btn btn-outline-danger" @onclick="() => ConfirmDelete(q)">Löschen</button>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

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

@code {
    private LocalDbContext? DataContext;
    private ModalComponent modal = null!;
    private Quiz? SelectedItem;

    private List<Quiz> QuizList { get; set; } = new();

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

    private async Task ShowList()
    {
        DataContext ??= await DbFactory.CreateDbContextAsync();
        if (DataContext != null)
        {
            QuizList = await DataContext.Quiz.OrderBy(q => q.Name).ToListAsync();
        }
    }

    private async Task ConfirmDelete(Quiz itm)
    {
        SelectedItem = itm;
        await modal.ShowAsync();
    }

    private async Task CloseDialog()
    {
        SelectedItem = null;
        await modal.CloseAsync();
    }

    private async Task DeleteItem(MouseEventArgs e)
    {
        if (SelectedItem != null)
        {
            DataContext ??= await DbFactory.CreateDbContextAsync();
            if (DataContext != null)
            {
                DataContext.Quiz.Remove(SelectedItem);
                await DataContext.SaveChangesAsync();
                await ShowList();
            }
        }
        await CloseDialog();
    }

}
