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

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

import com.google.common.collect.Lists;

import de.bstly.board.model.Bookmarks;
import de.bstly.board.model.QBookmarks;
import de.bstly.board.model.QLocalUser;
import de.bstly.board.repository.BookmarksRepository;
import de.bstly.board.repository.EntryRepository;
import de.bstly.board.repository.LocalUserRepository;

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

	@Autowired
	private BookmarksRepository bookmarksRepository;
	@Autowired
	private EntryRepository entryRepository;
	@Autowired
	private LocalUserRepository localUserRepository;
	private QLocalUser qLocalUser = QLocalUser.localUser;
	private QBookmarks qBookmarks = QBookmarks.bookmarks;

	/**
	 * Gets the.
	 *
	 * @param username the username
	 * @return the bookmarks
	 */
	public Bookmarks get(String username) {
		return bookmarksRepository.findOne(qBookmarks.username.equalsIgnoreCase(username))
				.orElse(new Bookmarks(username));
	}

	/**
	 * Checks for entry.
	 *
	 * @param username the username
	 * @param entryId the entry id
	 * @return true, if successful
	 */
	public boolean hasEntry(String username, Long entryId) {
		return bookmarksRepository.exists(qBookmarks.username.equalsIgnoreCase(username)
				.and(qBookmarks.entries.contains(entryId)));
	}

	/**
	 * Adds the entry.
	 *
	 * @param username the username
	 * @param entryId the entry id
	 */
	public void addEntry(String username, Long entryId) {
		Assert.isTrue(entryRepository.existsById(entryId), "Invalid entryid");
		Assert.isTrue(localUserRepository.exists(qLocalUser.username.equalsIgnoreCase(username)),
				"Invalid username");
		Bookmarks bookmarks = get(username);

		if (bookmarks.getEntries() == null) {
			bookmarks.setEntries(Lists.newArrayList());
		}

		if (!hasEntry(username, entryId)) {
			bookmarks.getEntries().add(entryId);
			bookmarksRepository.save(bookmarks);
		}
	}

	/**
	 * Removes the entry.
	 *
	 * @param username the username
	 * @param entryId the entry id
	 */
	public void removeEntry(String username, Long entryId) {
		Assert.isTrue(entryRepository.existsById(entryId), "Invalid entryid");
		Assert.isTrue(localUserRepository.exists(qLocalUser.username.equalsIgnoreCase(username)),
				"Invalid username");

		Bookmarks bookmarks = get(username);

		if (bookmarks.getEntries() == null) {
			bookmarks.setEntries(Lists.newArrayList());
		}

		if (hasEntry(username, entryId)) {
			bookmarks.getEntries().remove(entryId);
			bookmarksRepository.save(bookmarks);
		}
	}

	/**
	 * Removes the entry.
	 *
	 * @param entryId the entry id
	 */
	public void removeEntry(Long entryId) {
		for (Bookmarks bookmarks : bookmarksRepository
				.findAll(qBookmarks.entries.contains(entryId))) {
			bookmarks.getEntries().remove(entryId);
			bookmarksRepository.save(bookmarks);
		}
	}

}
