@using Microsoft.EntityFrameworkCore
@page "/teams"
@attribute [Authorize]
@inject AppDbContext Context
@inject IDialogService DialogService
@inject ISnackbar Snackbar

<PageTitle>TimeSlots</PageTitle>

<MudText Typo="Typo.h3">Teams</MudText>

<MudButton StartIcon="@Icons.Material.Filled.Create" Href="teams/create">Create New</MudButton>
<MudButton StartIcon="@Icons.Material.Filled.Assignment" Href="teams/assignment">Assignment</MudButton>
<MudButton StartIcon="@Icons.Material.Filled.Print" Href="teams/printout">Printout</MudButton>


<MudDataGrid T="Team" ServerData="ServerReload" @ref="_dataGrid" Filterable="true" RowsPerPage="35">
    <Columns>
        <TemplateColumn Title="Event">
            <CellTemplate>
                @context.Item.ToString()
            </CellTemplate>
        </TemplateColumn>
        <TemplateColumn Title="Attributes">
            <CellTemplate>
                <EventAttributes EventDefinition="@context.Item.Event"></EventAttributes>
            </CellTemplate>
        </TemplateColumn>
        <TemplateColumn Title="Students">
            <CellTemplate>
                <TeamStudents Team="@context.Item"></TeamStudents>
            </CellTemplate>
        </TemplateColumn>
        <TemplateColumn>
            <CellTemplate>
                <CrudActions
                    DetailsHref="@($"/teams/details?id={context.Item!.Id}")"
                    EditHref="@($"/teams/edit?id={context.Item!.Id}")"
                    DeleteOnClick="() => DeleteTeam(context.Item!)">
                </CrudActions>
            </CellTemplate>
        </TemplateColumn>
    </Columns>
    <PagerContent>
        <MudDataGridPager T="Team"></MudDataGridPager>
    </PagerContent>
</MudDataGrid>

@code {
    MudDataGrid<Team> _dataGrid = null!;

    private async Task<GridData<Team>> ServerReload(GridState<Team> state)
    {
        var query 
            = Context.Teams
                .Include(e => e.Event)
                .Include(e => e.Students)
                .ThenInclude(e => e.EventRankings)
                .OrderBy(e => e.Event.Name)
                .ThenBy(e => e.Identifier)
                .Where(state.FilterDefinitions)
                .OrderBy(state.SortDefinitions);

        var totalItems = await query.CountAsync();
        var pagedData = await query.Skip(state.Page * state.PageSize).Take(state.PageSize).ToArrayAsync();

        return new GridData<Team>
        {
            TotalItems = totalItems,
            Items = pagedData
        };
    }

    private async Task DeleteTeam(Team team)
    {
        //_isRowBlocked = true;

        var result = await DialogService
            .ShowMessageBox("Delete team",
                (MarkupString)$"Are you sure want to delete <b>{team}</b>? This cannot be undone.",
                yesText: "Yes",
                noText: "Cancel");

        if (result == true)
        {
            // If deleting a numbered team (1 or 2), clear the identifier of the remaining team
            if (team.Identifier == "1" || team.Identifier == "2")
            {
                var remainingTeam = await Context.Teams
                    .Include(t => t.Event)
                    .FirstOrDefaultAsync(t => t.Event.Id == team.Event.Id && t.Id != team.Id);

                if (remainingTeam != null)
                {
                    remainingTeam.Identifier = null;
                    Context.Teams.Update(remainingTeam);
                }
            }

            Context.Teams.Remove(team!);
            await Context.SaveChangesAsync();
            Snackbar.Add($"Delete event: Delete of Team {team}", Severity.Info);
        }

        //_isRowBlocked = false;
        StateHasChanged();
        _dataGrid.ReloadServerData();
    }
}
