@using ServerManagement.StateStore

@implements IDisposable

@inject EindhovenOnlineServersStore EindhovenOnlineServersStore

<div class="col">
  <div class="card @((city == selectedCity) ? "border-primary" : "")">
    <img src=@($"/images/{@city}.png") class="card-img-top" alt="@city">
    <div class="card-body @((city == selectedCity) ? "active" : "")">
      <button class="btn btn-primary" @onclick="@(() => { SelectCity(city); })">@city</button>
    </div>
    <div>
      @if (city.Equals("Eindhoven", StringComparison.OrdinalIgnoreCase))
      {
        <text>Online: @serversOnlineEindhoven</text>
      }
    </div>
  </div>
</div>

@code {
  private int serversOnlineEindhoven;
  [Parameter]
  public string? city { get; set; } = "";

  [Parameter]
  public string? selectedCity { get; set; } = "Eindhoven";

  [Parameter]
  public EventCallback<string> SelectCityCallBack { get; set; }

  private void SelectCity(string cityName)
  {
    SelectCityCallBack.InvokeAsync(cityName);
  }

  protected override void OnAfterRender(bool firstRender)
  {
    if (firstRender)
    {
      serversOnlineEindhoven = EindhovenOnlineServersStore.GetNumberServersOnline();
      EindhovenOnlineServersStore.AddStateChangeListener(OnServersStatusChange);
      StateHasChanged();
    }
  }

  private void OnServersStatusChange()
  {
    serversOnlineEindhoven = EindhovenOnlineServersStore.GetNumberServersOnline();
    StateHasChanged();
  }

  // Remove the listeners, otherwise it can cause memory leaks.
  public void Dispose()
  {
    EindhovenOnlineServersStore.RemoveStateChangeListener(OnServersStatusChange);
  }
}