/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.dom;

import java.util.Collection;

import org.w3c.dom.Element;

import woolpack.el.GettingEL;
import woolpack.utils.CheckUtils;
import woolpack.utils.UtilsConstants;

/**
 * DOM 属性名に対応する属性値が値の一覧に含まれることを評価した結果を返す{@link Evaluable}。
 * 
 * @author nakamura
 * 
 */
public class EvalAttrValueContains implements Evaluable<Boolean> {
	private final String attrName;

	private final GettingEL valueEL;

	/**
	 * コンストラクタ。
	 * 
	 * @param attrName
	 *            属性名。
	 * @param valueEL
	 *            値の一覧への参照。コンテキスト役に対して副作用が発生すべきではない。
	 * @throws NullPointerException
	 *             引数のいずれかが null の場合。
	 * @throws StringIndexOutOfBoundsException
	 *             attrName が空の場合。
	 */
	public EvalAttrValueContains(
			final String attrName,
			final GettingEL valueEL) {
		CheckUtils.checkNotEmpty(attrName);
		CheckUtils.checkNotNull(valueEL);

		this.attrName = attrName;
		this.valueEL = valueEL;
	}

	public Boolean eval(final DomContext context) {
		final Object value = valueEL.getValue(context);
		final Collection collection = UtilsConstants.toCollection(value);
		final String elementValue = ((Element) context.getNode())
				.getAttribute(attrName);

		boolean containsFlag = false;
		for (final Object o : collection) {
			// 属性値は文字列なので文字列に変換して比較する
			if (o != null && o.toString().equals(elementValue)) {
				containsFlag = true;
				break;
			}
		}
		return containsFlag;
	}
}
