/**
 * 
 */
package de.bstly.board.controller.validation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import de.bstly.board.businesslogic.CommentManager;
import de.bstly.board.businesslogic.EntryManager;
import de.bstly.board.model.Comment;


/**
 * The Class CommentValidator.
 */
@Component
public class CommentValidator implements Validator {

	@Autowired
	private CommentManager commentManager;
	@Autowired
	private EntryManager entryManager;


	/*
	 * @see org.springframework.validation.Validator#supports(java.lang.Class)
	 */
	@Override
	public boolean supports(Class<?> clazz) {
		return clazz.isAssignableFrom(Comment.class);
	}


	/*
	 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
	 */
	@Override
	public void validate(Object target, Errors errors) {
		Comment comment = (Comment) target;
		if (comment.getTarget() == null) {
			errors.rejectValue("target", "REQUIRED");
		} else if (!entryManager.exists(comment.getTarget())) {
			errors.rejectValue("target", "INVALID");
		}

		if (comment.getParent() != null) {
			Comment parent = commentManager.get(comment.getParent());
			if (parent == null || !parent.getTarget().equals(comment.getTarget())) {
				errors.rejectValue("parent", "INVALID");
			}
		}

		if (!StringUtils.hasText(comment.getText())) {
			errors.rejectValue("text", "REQUIRED");
		}
	}

}
