/*
 * This file is part of Nuts Framework.
 * Copyright (C) 2009 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 java.io.IOException;
import java.util.Iterator;

import nuts.core.lang.StringUtils;
import nuts.exts.struts2.views.java.AbstractTemplateRenderer;
import nuts.exts.struts2.views.java.Attributes;

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

/**
 * Base class for ActionError and ActionMessage
 */
public abstract class AbstractMessageListRenderer extends
		AbstractTemplateRenderer {
	public AbstractMessageListRenderer(TemplateRenderingContext context) {
		super(context);
	}

	public void render() throws IOException {
		Object errorsObj = findValue(getListExpression());

		if (errorsObj != null) {
			boolean ul = false;
			
			Iterator itt = MakeIterator.convert(errorsObj);
			while (itt.hasNext()) {
				String error = (String)itt.next();
				if (StringUtils.isNotEmpty(error)) {
					if (!ul) {
						Attributes attrs = new Attributes();
						attrs.id(params).cssStyle(params)
							.add("class", defs((String)params.get("cssClass"), getDefaultClass()));
						stag("ul", attrs);
						ul = true;
					}
					// li for each error
					stag("li", null);

					// span for error
					stag("span", null);
					body(error, Attributes.isTrue(params.get("escape")));
					etag("span");
					etag("li");
				}
			}
			if (ul) {
				etag("ul");
			}
		}
	}

	/*
	 * Expression used to get list from stack
	 */
	protected abstract String getListExpression();

	/*
	 * default class for UL element
	 */
	protected abstract String getDefaultClass();
}
