package de.champonthis.buntspecht.controller.admin.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.champonthis.buntspecht.businesslogic.UserManager;
import de.champonthis.buntspecht.model.User;

@Component
public class UserValidator implements Validator {

    @Autowired
    private UserManager userManager;

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(User.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        User user = (User) target;
        if (!StringUtils.hasText(user.getUsername())) {
            errors.rejectValue("username", "REQUIRED");
            return;
        }
    }

    public void validateNew(Object target, Errors errors) {
        validate(target, errors);

        if (errors.hasErrors()) {
            return;
        }

        User user = (User) target;
        if (userManager.exists(user.getUsername())) {
            errors.rejectValue("username", "ALREADY_EXISTS");
            return;
        }
    }

}
