@page "/links/{id:guid}"
@inject LinksClient Links
@inject CommentsClient Comments
@inject NotificationManager Notification

@if (_link == null)
{
  <Title Value="Loading link detail..." />
  <p>Loading link detail...</p>
}
else
{
  <Title Value="@($"Viewing link {_link.Url}")" />
  
  <h1>Viewing link @_link.Url</h1>

  @if(_comments == null)
  {
    <p>Loading link comments...</p>
  }
  else if (_comments.Count == 0)
  {
    <p>No comments yet.</p>
  }
  else
  {
    <ul>
      @foreach (var comment in _comments)
      {
          <li>@comment.Content</li>
      }
    </ul>
  }

  <AuthorizeView>
    <Authorized>
      <CommentForm OnSubmit="PublishComment" />
    </Authorized>
    <NotAuthorized>
      <p>You should log in to comment!</p>
    </NotAuthorized>
  </AuthorizeView>
}

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

  private LinkDTO _link;
  private ICollection<CommentDTO> _comments;

  protected override async Task OnInitializedAsync()
  {
    _link = await Links.GetByIdAsync(Id);
    _comments = await Links.CommentsAsync(Id);
  }

  private async Task PublishComment(PublishCommentCommand cmd)
  {
    cmd.LinkId = Id;
    await Comments.CreateAsync(cmd);
    Notification.Add("Your comment was published!");
    _comments = await Links.CommentsAsync(Id);
  }
}