/*
 * 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.utils;

import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * {@link javax.xml.xpath}パッケージを使用して DOM ノードを検索する{@link NodeFindableFactory}。
 * 委譲先でノードを操作した場合、次の検索結果に影響する(スナップショットではない)。 適用しているパターン：Adapter。
 * 
 * @author nakamura
 * 
 */
public class NodeFindableFactoryImpl implements NodeFindableFactory {
	
	public NodeFindableFactoryImpl() {
	}

	/**
	 * @throws IllegalArgumentException (
	 *             {@link XPathExpressionException})XPath のコンパイルに失敗した場合。
	 */
	public NodeFindable newInstance(final String criteria) {
		compile(criteria);
		return new NodeFindable() {
			public NodeList evaluateList(final Object node) {
				return (NodeList) evaluate(criteria, XPathConstants.NODESET,
						node);
			}

			public Node evaluateOne(final Object node) {
				return (Node) evaluate(criteria, XPathConstants.NODE, node);
			}
		};
	}

	private static XPathExpression compile(final String s) {
		final XPath base = XPathFactory.newInstance().newXPath();
		try {
			return base.compile(s);
		} catch (final XPathExpressionException e) {
			throw new IllegalArgumentException(e);
		}
	}

	private static Object evaluate(
			final String s,
			final QName kind,
			final Object node) {
		final XPathExpression expression = compile(s);
		try {
			return expression.evaluate(node, kind);
		} catch (final XPathExpressionException e) {
			throw new IllegalStateException(e);
		}
	}
}
