/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.xwork2.validator.validators;

import java.util.Iterator;
import java.util.Map;

import org.apache.struts2.util.MakeIterator;


/**
 * <!-- START SNIPPET: javadoc -->
 * Field Validator that checks if the value specified is not within the prohibited value list.
 * <!-- END SNIPPET: javadoc -->
 *
 *
 * <!-- START SNIPPET: parameters -->
 * <ul>
 * 		<li>fieldName - The field name this validator is validating. Required if using Plain-Validator Syntax otherwise not required</li>
 * 		<li>constants - the constants of the value. Required. </li>
 *      </li>
 * </ul>
 * <!-- END SNIPPET: parameters -->
 *
 *
 * <pre>
 * <!-- START SNIPPET: examples -->
 * 		&lt;validators>
 *           &lt;!-- Plain Validator Syntax --&gt;
 *           &lt;validator type="prohibited">
 *               &lt;param name="fieldName"&gt;name&lt;/param&gt;
 *               &lt;param name="constants"&gt;1,2,3&lt;/param&gt;
 *               &lt;message&gt;value should not in ${constants}&lt;/message&gt;
 *           &lt;/validator&gt;
 *
 *           &lt;!-- Field Validator Syntax --&gt;
 *           &lt;field name="name"&gt;
 *               &lt;field-validator type="prohibited"&gt;
 *                   &lt;param name="constants"&gt;"a","b","c"&lt;/param&gt;
 *                   &lt;message&gt;value should not in ${constants}&lt;/message&gt;
 *               &lt;/field-validator&gt;
 *           &lt;/field&gt;
 *      &lt;/validators&gt;
 * <!-- END SNIPPET: examples -->
 * </pre>
 *
 */
public class ProhibitedFieldValidator extends ConstantFieldValidator {

	protected boolean validate(Object object, Object value, Object constants) {
		Iterator iterator = null;
		if (MakeIterator.isIterable(constants)) {
			iterator = MakeIterator.convert(constants);
			while (iterator.hasNext()) {
				Object v = iterator.next();
				if (v instanceof Map.Entry) {
					v = ((Map.Entry)v).getKey();
				}
	
				if (v != null) {
					if (ignoreCase) {
						if (v.toString().equalsIgnoreCase(value.toString())) {
							addFieldError(getFieldName(), object);
							return false;
						}
					}
					else {
						if (v.toString().equals(value.toString())) {
							addFieldError(getFieldName(), object);
							return false;
						}
					}
				}
			}
		}
		return true;
	}
}
