@page "/"
@using FWLAZ_Web.Data
@using FWLAZ_Web.Objects
@using Microsoft.EntityFrameworkCore
@inject Blazored.LocalStorage.ILocalStorageService localStorage;
@inject IDbContextFactory<LocalDbContext> DbFactory;
@inject SessionState CurrentSession;
@inject NavigationManager nav;

<PageTitle>Home</PageTitle>

@if (CurrentSession.LoadGame != null)
{
    <h1>Vorherigen Lauf fortsetzen</h1>
    <div>@CurrentSession.LoadGame.Title</div>
    <button class="btn btn-primary" type="button" @onclick="() => StartQuiz(CurrentSession.LoadGame)">Fortsetzen</button>
    <button class="btn btn-outline-danger" type="button" @onclick="DeleteGameState">Löschen</button>
}


<h1>Neues Quiz beginnen</h1>

<div class="d-grid gap-2">
    @foreach (Quiz quiz in QuizList)
    {
        <button type="submit" class="btn btn-primary" @onclick="() => OpenDialog(quiz)">@quiz.Name</button>
    }
</div>

<ModalDialog @ref="modal">
    <Title>
        @SelectedQuiz?.Name;
    </Title>
    <Body>
        @if (SelectedQuiz != null && NewGame != null)
        {
@*             <div class="mb-3">
                <label for="btngrpMode" class="form-label">Modus</label>
                <div class="btn-group form-control" id="btngrpMode">
                    <a href="#" @onclick="() => NewGame.Mode =  GameState.QuizMode.Practice" class="btn @(NewGame.Mode == GameState.QuizMode.Practice ? "btn-primary active" : "btn-outline-primary")">Üben</a>
                    <a href="#" @onclick="() => NewGame.Mode =  GameState.QuizMode.Tournament" class="btn @(NewGame.Mode == GameState.QuizMode.Tournament ? "btn-primary active" : "btn-outline-primary")">Rangliste</a>
                </div>
            </div> *@

            <div class="mb-3">
                <label for="cboQuestionGroup" class="form-label">Fragenkatalog</label>
                <select @bind="QuestionGroupId" class="form-select" id="cboQuestionGroup" aria-label="Select Question group">
                    @foreach (QuestionGroup questionGroup in SelectedQuiz.Questiongroups)
                    {
                        <option value="@questionGroup.Id">@questionGroup.Name</option>
                    }
                </select>
            </div>

            <div class="mb-3">
                <label for="rngQuestionCount" class="form-label">Anzahl der Fragen: @QuestionCountValue</label>
                <input type="range" min="1" max="@QuestionCountMax" @bind="@QuestionCountValue" class="form-range" id="rngQuestionCount">
            </div>

@*             <div class="mb-3">
                <label for="txtName" class="form-label">Name</label>
                <input @bind="NewGame.Username" class="form-control" type="text" placeholder="(optional)" id="txtName" />
            </div> *@
        }
    </Body>
    <Footer>
        @if (NewGame != null)
        {
            <button class="btn btn-danger" @onclick="() => StartQuiz(NewGame)">Start</button>
        }
        <button class="btn btn-primary" @onclick="CloseDialog">Abbruch</button>
    </Footer>
</ModalDialog>

@code {
    public List<Quiz> QuizList { get; set; } = new();
    private LocalDbContext? DbContext;
    private ModalDialog modal = null!;
    private GameState? NewGame;
    private GameState? LoadGame;
    private Quiz? SelectedQuiz;
    private static Random rng = new();

    private int _QuestionGroupId;
    public int QuestionGroupId
    {
        get
        {
            return _QuestionGroupId;
        }
        set
        {
            _QuestionGroupId = value;
            QuestionCountMax = SelectedQuiz?.Questiongroups.Single(qg => qg.Id == value).Questions.Count ?? 0;
            QuestionCountValue = QuestionCountMax;
            //  QuestionCountValue = Math.Min(QuestionCountMax, QuestionCountValue);
        }
    }
    public int QuestionCountMax { get; set; } = 1;
    public int QuestionCountValue { get; set; } = 20;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender) await CurrentSession.LoadAsync();
    }

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

    private async Task FillListAsync()
    {
        DbContext ??= await DbFactory.CreateDbContextAsync();
        if (DbContext == null) return;
        QuizList = await DbContext.Quiz.OrderBy(q => q.Name).ToListAsync();
    }

    private async Task OpenDialog(Quiz itm)
    {
        DbContext ??= await DbFactory.CreateDbContextAsync();
        if (DbContext == null) return;
        SelectedQuiz = DbContext.Quiz.Include(q => q.Questiongroups).ThenInclude(qg => qg.Questions).Single(q => q.Id == itm.Id);
        QuestionGroupId = SelectedQuiz.Questiongroups.First().Id;
        NewGame = new GameState(SelectedQuiz);
        await InvokeAsync(StateHasChanged);
        await modal.ShowAsync();
    }

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

    private async Task StartQuiz(GameState state)
    {
        if (state.Questions == null)
        {
            // Bei neuem Spiel - Frageliste füllen
            DbContext ??= await DbFactory.CreateDbContextAsync();
            if (DbContext == null || state == null) return;
            state.Questions = DbContext.QuestionGroup
            .Include(qg => qg.Questions)
            .ThenInclude(q => q.Answers)
            .Single(qg => qg.Id == QuestionGroupId).Questions.OrderBy(_ => rng.Next()).ToList();
            state.Questions = state.Questions.Take(QuestionCountValue).ToList();
            CurrentSession.LoadGame = state;
            await CurrentSession.SaveAsync();
        }
        if (state != null) nav.NavigateTo($"quizstart");
        await CloseDialog();
    }
    private async Task DeleteGameState(MouseEventArgs e)
    {
        CurrentSession.LoadGame = null;
        await localStorage.RemoveItemAsync(GameState.STORAGEKEY);

    }
}
