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

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;

import woolpack.fn.Fn;

/**
 * {@link javax.xml.xpath.XPath}を使用して DOM ノードを検索する{@link NodeFindable}のファクトリです。
 * 委譲先でノードを操作した場合、次の検索結果に影響します(スナップショットではありません)。
 * <br/>適用しているデザインパターン：Abstract Factory。
 * 
 * @author nakamura
 * 
 */
public class NodeFindableFactory implements Fn<String, NodeFindable> {

	/**
	 * @throws IllegalArgumentException ({@link XPathExpressionException})XPath のコンパイルに失敗した場合。
	 */
	public NodeFindable exec(final String c) {
		compile(c);
		return new NodeFindable() {
			public NodeList evaluateList(final Object node) {
				return (NodeList) evaluate(c, XPathConstants.NODESET, node);
			}
			public Node evaluateOne(final Object node) {
				return (Node) evaluate(c, 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);
		}
	}
}
