@page "/servers"
@page "/servers/back_from/{cityName}"

@using ServerManagement.Components.Controls

@inject NavigationManager NavigationManager
@inject EindhovenOnlineServersStore EindhovenOnlineServersStore

<h3>Servers</h3>
<br/>
<br/>
<CityListComponent
  @ref="cityListComponent"
  SelectCityCallBack="HandleCitySelection"
  selectedCity="@this.selectedCity">
</CityListComponent>
<br/>
<SearchBarComponent
  @ref="searchBarComponent"
  FilterSearchTerm="HandleSearch"
  style="width: 600px">
</SearchBarComponent>
<br/>
<a href="@($"/server")" class="btn btn-primary">Add Server</a>
&nbsp;
<a href="@($"/servername")" class="btn btn-primary">Wizard</a>
<br/>

<CascadingValue Name="SelectedCity" Value="@selectedCity">
  <ServerListComponent
    CityName="@this.selectedCity"
    SearchFilter="@this.searchFilter">
  </ServerListComponent>
</CascadingValue>

@code {
  [Parameter]
  public string? CityName { get; set; }
  private string selectedCity = "Eindhoven";
  private string searchFilter = "";
  private CityListComponent? cityListComponent;
  private SearchBarComponent? searchBarComponent;

  private void HandleCitySelection(string cityName)
  {
    this.selectedCity = cityName;
    this.searchFilter = string.Empty;
    searchBarComponent?.ClearFilter();
  }

  private void HandleSearch(string searchFilter)
  {
    this.searchFilter = searchFilter;
    cityListComponent?.ClearSelection();
  }

  protected override void OnAfterRender(bool firstRender)
  {
    if (firstRender)
    {
      if (NavigationManager.Uri.Contains("back_from") && !string.IsNullOrWhiteSpace(CityName))
      {
        selectedCity = CityName;
        StateHasChanged();
      }

      var serversEindhoven = ServersRepository.GetServersByCity("Eindhoven");
      if (serversEindhoven != null)
      {
        EindhovenOnlineServersStore.SetNumberServersOnline(serversEindhoven.Count(s => s.IsOnline));
      }
    }
  }
}