@page "/register"
@inject AccountsClient Accounts
@inject NotificationManager Notifications
@inject NavigationManager Navigation

<Title Value="Créer un compte" />

<EditForm Model="@_model" OnValidSubmit="TryRegister">
  <DataAnnotationsValidator />
  <ValidationSummary />

  <InputText @bind-Value="_model.Username" />
  <InputText type="password" @bind-Value="_model.Password" />
  <InputText type="password" @bind-Value="_model.ConfirmPassword" />

  <button type="submit">S'enregistrer</button>
</EditForm>

@code {
  private RegisterViewModelClient _model = new RegisterViewModelClient();

  public class RegisterViewModelClient
  {
    public RegisterViewModel Model { get; private set; } = new RegisterViewModel();

    [System.ComponentModel.DataAnnotations.Required]
    public string Username { get => Model.Username; set => Model.Username = value; }
    
    [System.ComponentModel.DataAnnotations.Required]
    public string Password { get => Model.Password; set => Model.Password = value; }

    [System.ComponentModel.DataAnnotations.Required]
    [System.ComponentModel.DataAnnotations.Compare(nameof(Password))]
    public string ConfirmPassword { get => Model.ConfirmPassword; set => Model.ConfirmPassword = value; }
  }

  private async Task TryRegister()
  {
    try
    {
      await Accounts.RegisterAsync(_model.Model);
      Notifications.Add("Votre compte a été créé !");
      Navigation.NavigateTo("/");
    }
    catch
    {
      Notifications.Add("Une erreur est survenue");
    }
  }
}