@page "/quickgrid"
@using Microsoft.AspNetCore.Components.QuickGrid

@inject NavigationManager NavigationManager

<h3>QuickGrid demo</h3>
<br/>

@if (servers != null)
{
  <QuickGrid Items="servers.AsQueryable()" Pagination="paginationState">
    <PropertyColumn Property="s => s.Name" Sortable="true"></PropertyColumn>
    <PropertyColumn Property="s => s.City" Sortable="true"></PropertyColumn>
    <TemplateColumn Title="Status" Sortable="true" SortBy="GridSort<Server>.ByAscending(s => s.IsOnline)">
        <div style="color: @(context.IsOnline ? "green" : "red")">
          @(context.IsOnline ? "Online" : "Offline")
        </div>
    </TemplateColumn>
    <TemplateColumn Title="People online">
      @if (context.IsOnline)
      {
        Random random = new Random();
        int randomNumber = random.Next(0, 500);
        <text>@randomNumber users online</text>
      }
      else
      {
        <text>N/A</text>
      }
    </TemplateColumn>
    <TemplateColumn>
      @if (context.IsOnline)
      {
        <button type="button" class="btn btn-outline-danger"
          @onclick="@(() => { context.IsOnline = false; })">
        Turn off
        </button>
      }
      else
      {
        <button type="button" class="btn btn-outline-success"
          @onclick="@(() => { context.IsOnline = true; })">
        Turn on
        </button>
      }
    </TemplateColumn>
    <TemplateColumn>
      <a href="@($"/servers/{context.Id}")" class="btn btn-primary">Edit</a>
    </TemplateColumn>

    <TemplateColumn>
      <ChildContent Context="server">
        <EditForm
          Model="server"
          FormName="@($"formDeleteServer{server.Id}")"
          OnValidSubmit="@(() => { DeleteServer(server.Id); })">
          <button type="submit" class="btn btn-danger">Delete</button>
        </EditForm>
      </ChildContent>
    </TemplateColumn>
  </QuickGrid>
  <Paginator State="paginationState"></Paginator>
}

@code {
  private List<Server>? servers = ServersRepository.GetServers();
  private PaginationState paginationState = new PaginationState { ItemsPerPage = 5 };
  private void DeleteServer(int serverId)
  {
    if (serverId > 0)
    {
      ServersRepository.DeleteServer(serverId);
      NavigationManager.Refresh(forceReload: true);
    }
  }
}