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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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.UserPageManager;
import de.bstly.board.controller.support.EntityResponseStatusException;
import de.bstly.board.model.UserPage;

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

	@Autowired
	private UserPageManager userPageManager;

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

	/*
	 * @see org.springframework.validation.Validator#validate(java.lang.Object,
	 * org.springframework.validation.Errors)
	 */
	@Override
	public void validate(Object target, Errors errors) {
		UserPage userPage = (UserPage) target;

		if (!StringUtils.hasText(userPage.getName())) {
			errors.rejectValue("name", "required");
		}

		if ((userPage.getId() == null || userPage.getId().equals(0L))
				&& userPageManager.exists(userPage.getUsername(), userPage.getName())) {
			errors.rejectValue("name", "ALREADY_EXISTS");
		}

		if (userPage.getId() != null) {
			UserPage origUserPage = userPageManager.get(userPage.getId());
			if (origUserPage == null) {
				errors.rejectValue("id", "INVALID");
			}

			if (!origUserPage.getUsername().equals(userPage.getUsername())) {
				throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
			}

			UserPage other = userPageManager.get(userPage.getUsername(), userPage.getName());
			if (other != null && !other.getId().equals(userPage.getId())) {
				errors.rejectValue("name", "ALREADY_EXISTS");
			}
		}

		if (userPage.getSorting() == null) {
			errors.rejectValue("sorting", "REQUIRED");
		}

	}

}
