/*
 * 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.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import org.w3c.dom.Element;

import woolpack.el.GettingEL;
import woolpack.fn.Fn;
import woolpack.utils.Utils;
import woolpack.xml.NodeContext;
import woolpack.xml.XmlUtils;

public class HiddenAppender<E extends Exception> implements Fn<NodeContext, Void, E> {
	private GettingEL mapEL;
	private Collection<String> excludeProperties;

	/**
	 * @param mapEL hidden にする情報が格納された{@link Map}への参照。
	 * @param excludeProperties hidden として追加しないキーの一覧。
	 */
	public HiddenAppender(
			final GettingEL mapEL,
			final Collection<String> excludeProperties) {
		this.mapEL = mapEL;
		this.excludeProperties = excludeProperties;
	}

	public Void exec(final NodeContext context) {
		final Map map = (Map) mapEL.getValue(context);
		for (final Object entryObject : map.entrySet()) {
			final Entry entry = (Entry) entryObject;
			if (excludeProperties.contains(entry.getKey())) {
				continue;
			}
			final Iterable<?> values = Utils.toIterable(entry.getValue());
			for (final Object value : values) {
				final Element e = XmlUtils.getDocumentNode(
						context.getNode()).createElement("INPUT");
				e.setAttribute("type", "hidden");
				e.setAttribute("name", entry.getKey().toString());
				e.setAttribute("value", value.toString());
				context.getNode().appendChild(e);
			}
		}
		return null;
	}

	public Collection<String> getExcludeProperties() {
		return excludeProperties;
	}
	public void setExcludeProperties(final Collection<String> excludeProperties) {
		this.excludeProperties = excludeProperties;
	}
	public GettingEL getMapEL() {
		return mapEL;
	}
	public void setMapEL(final GettingEL mapEL) {
		this.mapEL = mapEL;
	}
}
