package org.iri_research.renkan.forms;

import org.iri_research.renkan.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Component
public class UserFormValidator implements Validator {

    @SuppressWarnings("unused")
    private Logger logger = LoggerFactory.getLogger(UserFormValidator.class);

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

    @Override
    public void validate(Object target, Errors errors) {
        UserForm userForm = (UserForm) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title",
                "renkan.error.name.empty");
        
        //TODO : check for user name unicity
        String pswd = userForm.getPassword();
        String pswdConf = userForm.getPasswordConfirm();
        
        if( (pswd == null && pswdConf != null)
            || ((pswd != null || pswdConf != null) && !pswd.equals(pswdConf))) {
            errors.rejectValue("password", "renkan.error.password.equals");
        }
        
        if(userForm.getId() == null && (pswd == null || pswd.length() == 0)) {
            errors.rejectValue("password", "renkan.error.password.missing");
        }
        
        if(userForm.getUserAuthorities() != null && !Constants.USER_ROLES_ALL.containsAll(userForm.getUserAuthorities())) {
            errors.rejectValue("userAuthorities", "renkan.error.authorities.bad_value", "Bad role value");
        }
    }

}
