using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using MyHN.Domain;

namespace MyHN.Application
{
  public class GetLinksQueryHandler : IRequestHandler<GetLinksQuery, LinkDto[]>
  {
    private readonly IContext _context;

    public GetLinksQueryHandler(IContext context)
    {
      _context = context;
    }

    public Task<LinkDto[]> Handle(GetLinksQuery request, CancellationToken cancellationToken)
    {
      var result = from link in _context.Links
                   join user in _context.Users on link.CreatedBy equals user.Id
                   select new LinkDto
                   {
                     Id = link.Id,
                     Url = link.Url,
                     CreatedAt = link.CreatedAt,
                     CreatedByName = user.UserName,
                     UpvotesCount = link.Votes.Count(v => v.Direction == VoteType.Up),
                     DownvotesCount = link.Votes.Count(v => v.Direction == VoteType.Down)
                   };

      return Task.FromResult(result.OrderByDescending(o => o.CreatedAt).ToArray());

      // return Task.FromResult(_context.Links.Select(o => new LinkDto
      // {
      //   Id = o.Id,
      //   Url = o.Url,
      //   CreatedAt = o.CreatedAt
      // }).OrderByDescending(o => o.CreatedAt).ToArray());
    }
  }
}