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

import woolpack.el.EL;
import woolpack.el.GettingEL;
import woolpack.fn.Fn;
import woolpack.utils.Utils;

public class TemplateCopier<C extends NodeContext, E extends Exception> implements Fn<C, Void, E> {
	private GettingEL collectionEL;
	private EL valueEL;
	private Fn<? super C, Void, ? extends E> fn;

	public TemplateCopier(
			final GettingEL collectionEL,
			final EL valueEL,
			final Fn<? super C, Void, ? extends E> fn) {
		this.collectionEL = collectionEL;
		this.valueEL = valueEL;
		this.fn = fn;
	}

	public Void exec(final C c) throws E {
		final Node base = c.getNode();
		final Object value1 = collectionEL.getValue(c);
		final Iterable<?> iterable = Utils.toIterable(value1);
		try {
			for (final Object value : iterable) {
				c.setNode(base.cloneNode(true));
				valueEL.setValue(c, value);
				fn.exec(c);
				base.getParentNode().insertBefore(c.getNode(), base);
			}
			XmlUtils.removeThis(base);
		} finally {
			c.setNode(base);
		}
		return null;
	}

	public GettingEL getCollectionEL() {
		return collectionEL;
	}
	public void setCollectionEL(final GettingEL collectionEL) {
		this.collectionEL = collectionEL;
	}
	public Fn<? super C, Void, ? extends E> getFn() {
		return fn;
	}
	public void setFn(final Fn<? super C, Void, ? extends E> fn) {
		this.fn = fn;
	}
	public EL getValueEL() {
		return valueEL;
	}
	public void setValueEL(final EL valueEL) {
		this.valueEL = valueEL;
	}
}
