/**
 * 
 */
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.ViewManager;
import de.bstly.board.controller.support.EntityResponseStatusException;
import de.bstly.board.model.View;

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

	@Autowired
	private ViewManager viewManager;

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

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

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

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

		if (view.getId() != null) {
			View origView = viewManager.get(view.getId());
			if (origView == null) {
				errors.rejectValue("id", "INVALID");
			}

			if (!origView.getUsername().equals(view.getUsername())) {
				throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
			}

			View other = viewManager.get(view.getUsername(), view.getName());
			if (other != null && !other.getId().equals(view.getId())) {
				errors.rejectValue("name", "ALREADY_EXISTS");
			}
		}

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

	}

}
