package com.mason.server.validator;

import java.util.Arrays;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

import com.mason.server.dao.jdo.UserDAO;
import com.mason.server.model.DbUser;

public class UserValidator extends BasicValidator {

	private static UserDAO userDAO = new UserDAO();

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

	private String[] usernames = { "user", "welcome", "model" };

	@Override
	public void validate(Object obj, Errors errors) {

		DbUser u = (DbUser) obj;
		if (u.equals(null)) {
			return;
		}

		if (u.getId() == null) {
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username",
					"description.null");

			if (!this.validateDescription(u.getUsername())) {
				errors.reject("username", "username.not.valid");
			}

			if (userDAO.getByUsername(u.getUsername()) != null
					|| Arrays.asList(usernames).contains(u.getUsername())) {
				errors.reject("username", "username.in.use");
			}
		}

	}

}
