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

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;


import org.cyberneko.html.parsers.DOMParser;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import woolpack.dom.DomContext;
import woolpack.dom.DomExpression;
import woolpack.utils.ReaderFactory;

/**
 * CyberNeko HTML Parserを使用して{@link Reader}からDOMノードを生成する{@link DomExpression}。
 * @author nakamura
 *
 */
public class ToNode implements DomExpression{
	private final ReaderFactory factory;
	
	public ToNode(final ReaderFactory factory){
		factory.getClass();
		this.factory = factory;
	}

	/**
	 * @throws NullPointerException 引数が null の場合。
	 * @throws {@link SAXException}または{@link IOException}を catch した場合。
	 */
	public void interpret(final DomContext context) {
		final DOMParser parser = new DOMParser();
		try {
			final Reader r = factory.newInstance(context.getId());
			if(r == null){
				throw new RuntimeException(new FileNotFoundException("not found: " + context.getId()));
			}
			try{
				parser.parse(new InputSource(r));
			} catch (final SAXException e) {
				throw new RuntimeException(e);
			}finally{
				r.close();
			}
		} catch (final IOException e) {
			throw new RuntimeException(e);
		}
		context.setNode(parser.getDocument());
	}
}
