/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.struts2.views.java.simple;

import nuts.exts.struts2.views.java.AbstractTemplateRenderer;
import nuts.exts.struts2.views.java.Attributes;

import java.io.IOException;
import java.util.Iterator;

import org.apache.struts2.components.template.TemplateRenderingContext;
import org.apache.struts2.util.ContainUtil;
import org.apache.struts2.util.MakeIterator;

public class RadioMapRenderer extends AbstractTemplateRenderer {
	public RadioMapRenderer(TemplateRenderingContext context) {
		super(context);
	}

	public void render() throws IOException {
		String id = (String)params.get("id");
		String name = (String)params.get("name");
		Object disabled = params.get("disabled");
        Object value = params.get("nameValue");

		Object listObj = params.get("list");
		if (listObj != null) {
			String listKey = (String)params.get("listKey");
			String listValue = (String)params.get("listValue");

			Iterator itt = MakeIterator.convert(listObj);
			while (itt.hasNext()) {
				Object item = itt.next();
				stack.push(item);

				// key
				Object itemKey = findValue(listKey != null ? listKey : "top");
				String itemKeyStr = defs(itemKey == null ? null
						: itemKey.toString());
				// value
				Object itemValue = findValue(listValue != null ? listValue
						: "top");
				String itemValueStr = defs(itemValue == null ? null
						: itemValue.toString());

				boolean checked = ContainUtil.contains(value, itemKey);

				Attributes ra = new Attributes();
				ra.add("type", "radio")
					.add("name", name)
					.add("id", id + itemKeyStr)
					.cssClass(params)
					.addIfExists("value", itemKeyStr)
					.addIfTrue("checked", checked)
					.addIfTrue("disabled", disabled)
					.tabindex(params)
					.title(params)
					.cssStyle(params)
					.commons(params)
					.events(params);

				xtag("input", ra);
				
				write("<label");
				write(" for=\"");
				write(html(id) + itemKeyStr);
				write("\">");
				body(itemValueStr);
				write("</label>");

				stack.pop();
			}
		}
	}
}
