/*
 * 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 java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;

import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Node;

import woolpack.fn.Fn;

/**
 * {@link Reader}と{@link XmlTransformer}を使用する{@link Node}のファクトリです。
 * @author nakamura
 *
 */
public class NodeFactory implements Fn<String, Node> {
	private Fn<? super String, ? extends Reader> readerFactory;
	private Fn<XmlTransformerContext, Void> transformer;
	
	public NodeFactory(
			final Fn<? super String, ? extends Reader> readerFactory,
			final Fn<XmlTransformerContext, Void> transformer) {
		this.readerFactory = readerFactory;
		this.transformer = transformer;
	}

	/**
	 * @throws IllegalStateException ({@link IOException})
	 */
	public Node exec(final String c) {
		final DOMResult result = new DOMResult();
		final Reader r = readerFactory.exec(c);
		if (r == null) {
			throw new IllegalStateException(new FileNotFoundException("not found : " + c));
		}
		try {
			final XmlTransformerContext context = new XmlTransformerContext();
			context.setSource(new StreamSource(r));
			context.setResult(result);
			transformer.exec(context);
			return result.getNode();
		} finally {
			try {
				r.close();
			} catch (final IOException e) {
				throw new IllegalStateException(e);
			}
		}
	}

	public Fn<? super String, ? extends Reader> getReaderFactory() {
		return readerFactory;
	}
	public void setReaderFactory(final Fn<? super String, ? extends Reader> readerFactory) {
		this.readerFactory = readerFactory;
	}
	public Fn<XmlTransformerContext, Void> getTransformer() {
		return transformer;
	}
	public void setTransformer(final Fn<XmlTransformerContext, Void> transformer) {
		this.transformer = transformer;
	}
}
