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

import org.apache.commons.validator.routines.UrlValidator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import de.bstly.board.model.Entry;
import de.bstly.board.model.support.EntryType;

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

	private UrlValidator urlValidator = new UrlValidator();

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

	/*
	 * @see org.springframework.validation.Validator#validate(java.lang.Object,
	 * org.springframework.validation.Errors)
	 */
	@Override
	public void validate(Object target, Errors errors) {
		Entry entry = (Entry) target;
		if (!StringUtils.hasText(entry.getTitle())) {
			errors.rejectValue("title", "REQUIRED");
		}

		if (entry.getEntryType() == null) {
			errors.rejectValue("entrytype", "REQUIRED");
		} else if (EntryType.LINK.equals(entry.getEntryType())
				&& !StringUtils.hasText(entry.getUrl())) {
			errors.rejectValue("url", "REQUIRED");
		} else if (!EntryType.LINK.equals(entry.getEntryType())
				&& !StringUtils.hasText(entry.getText())) {
			errors.rejectValue("text", "REQUIRED");
		}

		if (StringUtils.hasText(entry.getUrl()) && !urlValidator.isValid(entry.getUrl())) {
			errors.rejectValue("url", "INVALID");
		}

		if (entry.getTags() != null) {
			for (String tag : entry.getTags()) {
				if (tag.contains("#")) {
					errors.rejectValue("tags", "INVALID", tag);
				}
			}
		}
	}

}
