/*
 * 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;
import woolpack.fn.NullFn;

/**
 * 子ノードとして DOM エレメントを挿入する{@link Fn}です。
 * 
 * @author nakamura
 * 
 * @param <C>
 */
public class ChildElementInserter<C extends NodeContext> implements Fn<C, Void> {
	private String elementName;
	private Fn<? super C, Void> fn;

	/**
	 * @param elementName エレメント名。
	 * @param fn 委譲先(ポインタは挿入したエレメント)。
	 */
	public ChildElementInserter(
			final String elementName,
			final Fn<? super C, Void> fn) {
		this.elementName = elementName;
		this.fn = fn;
	}

	/**
	 * @param elementName エレメント名。
	 */
	public ChildElementInserter(final String elementName) {
		this(elementName, new NullFn<NodeContext, Void>());
	}

	public Void exec(final C c) {
		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> getFn() {
		return fn;
	}
	public void setFn(final Fn<? super C, Void> fn) {
		this.fn = fn;
	}
}
