@using System.Threading;

@inject IServersEFCoreRepository ServersEFCoreRepository

<table class="table table-striped">
  <RepeaterComponent Items="this.servers">
    <Header>
      <thead>
        <tr>
          <th>Name</th>
          <th>City</th>
          <th>Status</th>
          <th>People online</th>
          <th></th>
          <th></th>
        </tr>
      </thead>
    </Header>
    <Row Context="server">
      <ServerComponent server="server"></ServerComponent>
    </Row>
    <Footer>

    </Footer>
  </RepeaterComponent>
</table>

<button type="button" class="btn btn-primary" onclick=@(() => {base.InvokeAsync(StateHasChanged);})"">Refresh</button>

@code {
  private List<Server>? servers;
  private Timer? Timer;

  [Parameter]
  public string? CityName { get; set; }
  [Parameter]
  public string SearchFilter { get; set; } = "";

  public override Task SetParametersAsync(ParameterView parameters)
  {
    // Only trigger OnParametersSet if the parameter matches and has actually changed.
    // This saves expensive calls to the data repository.
    if (parameters.TryGetValue<string>("CityName", out var cityName))
    {
      if (cityName != CityName)
      {
        base.SetParametersAsync(parameters);
      }
    }

    if (parameters.TryGetValue<string>("SearchFilter", out var searchFilter))
    {
      if (searchFilter != SearchFilter)
      {
        base.SetParametersAsync(parameters);
      }
    }

    return Task.CompletedTask;
  }

  protected override void OnParametersSet()
  {
    if (string.IsNullOrWhiteSpace(this.SearchFilter))
    {
      servers = ServersEFCoreRepository.GetServersByCity(CityName ?? "Eindhoven");
    }
    else
    {
      servers = ServersEFCoreRepository.SearchServers(SearchFilter);
    }
  }

  protected override void OnAfterRender(bool firstRender)
  {
    base.OnAfterRender(firstRender);

    if (firstRender)
    {
      if (string.IsNullOrWhiteSpace(this.SearchFilter))
      {
        servers = ServersEFCoreRepository.GetServersByCity(CityName ?? "Eindhoven");
      }
      else
      {
        servers = ServersEFCoreRepository.SearchServers(SearchFilter);
      }
      // Render the component again by letting it know the state changed.
      StateHasChanged();

      Timer = new Timer(_ => {
        base.InvokeAsync(StateHasChanged);
      }, null, 4000, 4000);
    }
  }
}