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

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

import org.w3c.dom.Node;

import woolpack.fn.Fn;

public class NodeFactory<C> implements Fn<C, Node, Exception> {
	private Fn<? super C, ? extends Reader, ? extends Exception> readerFactory;
	private Fn<XmlTransformerContext, Void, ? extends Exception> transformer;
	
	public NodeFactory(
			final Fn<? super C, ? extends Reader, ? extends Exception> readerFactory,
			final Fn<XmlTransformerContext, Void, ? extends Exception> transformer) {
		this.readerFactory = readerFactory;
		this.transformer = transformer;
	}

	public Node exec(final C c) throws Exception {
		final DOMResult result = new DOMResult();
		final Reader r = readerFactory.exec(c);
		if (r == null) {
			throw 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 {
			r.close();
		}
	}

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