@page "/server/{id:int?}"

@inject NavigationManager NavigationManager
@inject IJSRuntime JSRuntime

<NavigationLock
  OnBeforeInternalNavigation="OnBeforeInternalNavigation"
  ConfirmExternalNavigation="true">
</NavigationLock>

@if (Id.HasValue)
{
  <h3>Edit server</h3>
}
else
{
  <h3>Add server</h3>
}

@if (server != null)
{
  <EditForm Model="server" FormName="formServer" OnValidSubmit="SubmitServer">
    <DataAnnotationsValidator></DataAnnotationsValidator>
    <ValidationSummary></ValidationSummary>

    @if (server.Id > 0)
    {
      <InputNumber @bind-Value="server.Id" hidden></InputNumber>
    }

    <FieldComponent Label="Name">
      <Control>
        <InputText @bind-Value="server.Name" class="form-control"></InputText>
      </Control>
      <ValidationControl>
        <ValidationMessage For="() => server.Name"></ValidationMessage>
      </ValidationControl>
    </FieldComponent>

    <FieldComponent Label="City">
      <Control>
        <InputText @bind-Value="server.City" class="form-control"></InputText>
      </Control>
      <ValidationControl>
        <ValidationMessage For="() => server.City"></ValidationMessage>
      </ValidationControl>
    </FieldComponent>

    <FieldComponent Label="Online">
      <Control>
        <InputCheckbox @bind-Value="server.IsOnline" class="form-check-input"></InputCheckbox>
      </Control>
    </FieldComponent>
    <br/>
    @if (server.Id > 0)
    {
      <button class="btn btn-primary" type="submit">Update</button>
    }
    else 
    {
      <button class="btn btn-primary" type="submit">Save</button>
    }
    &nbsp;
    <a href="/servers" class="btn btn-primary">Close</a>
  </EditForm>
}

@code {
  [Parameter]
  public int? Id { get; set; }

  [SupplyParameterFromForm]
  private Server? server { get; set; }

  [SupplyParameterFromQuery]
  public string? City { get; set; }

  protected override void OnParametersSet()
  {
    if (this.Id.HasValue)
    {
      server ??= ServersRepository.GetServerById(this.Id.Value);
    }
    else
    {
      server ??= new Server() { IsOnline = false };
    }

    if (server != null && !string.IsNullOrEmpty(this.City))
    {
      server.City = this.City;
    }
  }

  private void SubmitServer()
  {
    if (server != null)
    {
      if (this.Id.HasValue)
      {
        ServersRepository.UpdateServer(server.Id, server);
      }
      else
      {
        ServersRepository.AddServer(server);
      }
    }

    // An exception is raised when debugging from VS Code, but not when using dotnet watch.
    NavigationManager.NavigateTo($"/servers/back_from/{this.server?.City}");
  }

  private async Task OnBeforeInternalNavigation(LocationChangingContext context)
  {
    var isConfirmed = await JSRuntime.InvokeAsync<bool>("confirm", "Are you sure you want to leave this page?");
    if (!isConfirmed)
    {
      context.PreventNavigation();
    }
  }
}