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

import java.util.List;

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

import com.querydsl.jpa.impl.JPAQueryFactory;

import de.bstly.board.model.QTag;
import de.bstly.board.model.Tag;
import de.bstly.board.repository.TagRepository;

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

	@Autowired
	private JPAQueryFactory jpaQueryFactory;
	@Autowired
	private TagRepository tagRepository;
	private QTag qTag = QTag.tag1;

	/**
	 * Creates the.
	 *
	 * @param tag the tag
	 * @param target the target
	 * @return the tag
	 */
	public Tag create(String tag, Long target) {
		return tagRepository.save(new Tag(tag, target));
	}

	/**
	 * Delete.
	 *
	 * @param tag the tag
	 * @param target the target
	 */
	public void delete(String tag, Long target) {
		tagRepository.deleteById(new Tag(tag, target));
	}

	/**
	 * Gets the for target.
	 *
	 * @param target the target
	 * @return the for target
	 */
	public List<String> getForTarget(Long target) {
		return jpaQueryFactory.selectFrom(qTag).where(qTag.target.eq(target)).select(qTag.tag)
				.fetch();
	}

	/**
	 * Sets the for target.
	 *
	 * @param target the target
	 * @param tags the tags
	 */
	public void setForTarget(Long target, List<String> tags) {
		deleteByTarget(target);
		if (tags != null) {
			for (String tag : tags) {
				create(tag, target);
			}
		}
	}

	/**
	 * Delete by target.
	 *
	 * @param target the target
	 */
	public void deleteByTarget(Long target) {
		tagRepository.deleteAll(tagRepository.findAll(qTag.target.eq(target)));
	}

	/**
	 * Search.
	 *
	 * @param search the search
	 * @return the list
	 */
	public List<String> search(String search) {
		return jpaQueryFactory.selectFrom(qTag).where(qTag.tag.containsIgnoreCase(search))
				.distinct().limit(10).select(qTag.tag).fetch();
	}

}
