using System;
using System.Linq;
using Domain;

namespace Application
{
  /// <summary>
  /// Service applicatif permettant la gestion des liens de la plateforme.
  /// </summary>
  public class LinkService
  {
    private readonly ILinkRepository _linkRepository;
    private readonly IData _data;

    public LinkService(ILinkRepository linkRepository, IData data)
    {
      _linkRepository = linkRepository;
      _data = data;
    }

    /// <summary>
    /// Publie un nouveau lien sur la plateforme.
    /// </summary>
    /// <param name="cmd"></param>
    /// <returns></returns>
    public Guid PublishLink(PublishLinkCommand cmd)
    {
      var link = new Link(cmd.Url);

      _linkRepository.Add(link);

      return link.Id;
    }

    /// <summary>
    /// Récupère tous les liens publiés jusqu'à présent.
    /// </summary>
    /// <returns></returns>
    public LinkDTO[] GetAllLinks()
    {
      return LinksDTO().ToArray();
    }

    public LinkDTO GetLinkById(Guid id)
    {
      return LinksDTO().Single(link => link.Id == id);
    }

    private IQueryable<LinkDTO> LinksDTO()
    {
      return (from link in _data.Links
              join comment in _data.Comments on link.Id equals comment.LinkId into comments
              orderby link.CreatedAt descending
              select new LinkDTO
              {
                Id = link.Id,
                Url = link.Url,
                CreatedAt = link.CreatedAt,
                UpvotesCount = 2,
                DownvotesCount = 4,
                CommentsCount = comments.Count(),
              });

      // return _data.Links
      //   .Select(link => new LinkDTO
      //   {
      //     Id = link.Id,
      //     Url = link.Url,
      //     CreatedAt = link.CreatedAt,
      //     UpvotesCount = 2,
      //     DownvotesCount = 4,
      //     CommentsCount = _data.Comments.Count(comment => comment.LinkId == link.Id),
      //   })
      //   .OrderByDescending(linkDto => linkDto.CreatedAt);
    }
  }
}
