aboutsummaryrefslogtreecommitdiff
path: root/src/DevHive.Services/Services/RatingService.cs
blob: 2c5a6b6371a6a979343c8347815ee08b012bd678 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using AutoMapper;
using DevHive.Data.Interfaces.Repositories;
using DevHive.Data.Models;
using DevHive.Services.Models.Post.Rating;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace DevHive.Services.Services
{
	public class RatingService
	{
		private readonly IPostRepository _postRepository;
		private readonly IRatingRepository _ratingRepository;
		private readonly IMapper _mapper;

		public RatingService(IPostRepository postRepository, IRatingRepository ratingRepository, IMapper mapper)
		{
			this._postRepository = postRepository;
			this._ratingRepository = ratingRepository;
			this._mapper = mapper;
		}

		public async Task<ReadRatingServiceModel> RatePost(RatePostServiceModel ratePostServiceModel)
		{
			if (!await this._postRepository.DoesPostExist(ratePostServiceModel.PostId))
				throw new ArgumentNullException("Post does not exist!");

			if (!await this._ratingRepository.HasUserRatedThisPost(ratePostServiceModel.UserId, ratePostServiceModel.PostId))
				throw new ArgumentException("You can't rate the same post more then one(duh, amigo)");

			Post post = await this._postRepository.GetByIdAsync(ratePostServiceModel.PostId);

			Rating rating = post.Rating;
			if (ratePostServiceModel.Liked)
				rating.Likes++;
			else
				rating.Dislikes++;

			bool success = await this._ratingRepository.EditAsync(rating.Id, rating);
			if (!success)
				throw new InvalidOperationException("Unable to rate the post!");

			Rating newRating = await this._ratingRepository.GetByIdAsync(rating.Id);
			return this._mapper.Map<ReadRatingServiceModel>(newRating);
		}

		public async Task<ReadRatingServiceModel> RemoveUserRateFromPost(Guid userId, Guid postId)
		{
			throw new NotImplementedException();
		}
	}
}