/**
 * 
 */
package de.bstly.board.businesslogic;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import de.bstly.board.model.QVote;
import de.bstly.board.model.Vote;
import de.bstly.board.model.support.Types;
import de.bstly.board.model.support.VoteType;
import de.bstly.board.repository.VoteRepository;

/**
 * The Class VoteManager.
 */
@Component
public class VoteManager {

	@Autowired
	private VoteRepository voteRepository;

	private QVote qVote = QVote.vote;

	/**
	 * Gets the.
	 *
	 * @param author the author
	 * @param target the target
	 * @param targetType the target type
	 * @return the vote
	 */
	public Vote get(String author, Long target, Types targetType) {
		return voteRepository.findOne(qVote.author.eq(author).and(qVote.targetType.eq(targetType))
				.and(qVote.target.eq(target))).orElse(null);
	}

	/**
	 * Save.
	 *
	 * @param vote the vote
	 * @return the vote
	 */
	public Vote save(Vote vote) {
		return voteRepository.save(vote);
	}

	/**
	 * Delete.
	 *
	 * @param vote the vote
	 */
	public void delete(Vote vote) {
		voteRepository.delete(vote);
	}

	/**
	 * Delete by target.
	 *
	 * @param target the target
	 * @param targetType the target type
	 */
	public void deleteByTarget(Long target, Types targetType) {
		for (Vote vote : voteRepository
				.findAll(qVote.target.eq(target).and(qVote.targetType.eq(targetType)))) {
			delete(vote);
		}
	}

	/**
	 * Gets the points.
	 *
	 * @param target the target
	 * @param targetType the target type
	 * @return the points
	 */
	public Long getPoints(Long target, Types targetType) {
		return voteRepository
				.count(qVote.target.eq(target)
						.and(qVote.targetType.eq(targetType).and(qVote.type.eq(VoteType.up))))
				- voteRepository.count(qVote.target.eq(target)
						.and(qVote.targetType.eq(targetType).and(qVote.type.eq(VoteType.down))));
	}

}
