@page "/links/new"
@inject LinksClient Links
@inject NavigationManager Navigation
@inject NotificationManager Notification
@using System.ComponentModel.DataAnnotations
@attribute [Authorize]

<h1>Publish a new link!</h1>

@if(_error != null) {
  <p>An error ! @_error.Message</p>
}

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

  <InputText @bind-Value="@_model.Url" />

  <button type="submit">Post!</button>
</EditForm>

@code {
  private Model _model = new Model();
  private Exception _error = null;

  private async Task TryPublishLink()
  {
    _error = null;

    try
    {
      await Links.CreateAsync(_model.Command);
      Notification.Add("Your link was published!");
      Navigation.NavigateTo("/");
    }
    catch(Exception ex)
    {
      _error = ex;
    }
  }

  private class Model
  {
    [Required]
    [Url]
    public string Url { get; set; }

    //public PublishLinkCommand Command { get { return new PublishLinkCommand { Url = new System.Uri(Url) }; }}
    public PublishLinkCommand Command => new PublishLinkCommand { Url = new System.Uri(Url) };
  }
}