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

namespace MyHN.Application
{
  public class GetLinkByIdQueryHandler : IRequestHandler<GetLinkByIdQuery, LinkDto>
  {
    private readonly IContext _context;

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

    public Task<LinkDto> Handle(GetLinkByIdQuery request, CancellationToken cancellationToken)
    {
      // var result = from link in _context.Links
      //              join user in _context.Users on link.CreatedBy equals user.Id
      //              where link.Id == request.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.Single());

      var result = _context.Links
        .Where(o => o.Id == request.Id)
        .Join(_context.Users,
          link => link.CreatedBy,
          user => user.Id,
          (link, user) => 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.Single());
    }
  }
}