/*
 * 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 org.w3c.dom.Element;
import org.w3c.dom.Node;

import woolpack.fn.Fn;

public class ChildElementInserter<C extends NodeContext, E extends Exception> implements Fn<C, Void, E> {
	private String elementName;
	private Fn<? super C, Void, ? extends E> fn;

	public ChildElementInserter(
			final String elementName,
			final Fn<? super C, Void, ? extends E> fn) {
		this.elementName = elementName;
		this.fn = fn;
	}

	public Void exec(final C c) throws E {
		final Node base = c.getNode();
		final Element element = XmlUtils.getDocumentNode(base).createElement(elementName);
		Node child = null;
		while ((child = base.getFirstChild()) != null) {
			element.appendChild(child);
		}
		base.appendChild(element);

		try {
			c.setNode(element);
			fn.exec(c);
		} finally {
			c.setNode(base);
		}
		return null;
	}

	public String getElementName() {
		return elementName;
	}
	public void setElementName(final String elementName) {
		this.elementName = elementName;
	}
	public Fn<? super C, Void, ? extends E> getFn() {
		return fn;
	}
	public void setFn(final Fn<? super C, Void, ? extends E> fn) {
		this.fn = fn;
	}
}
