/*
 * 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.core.lang.Strings;
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.MakeIterator;

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

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

		if (errorsObj != null) {
			boolean ul = false;
			Attributes attrsLI = new Attributes();

			Iterator itt = MakeIterator.convert(errorsObj);
			while (itt.hasNext()) {
				String error = (String)itt.next();
				if (Strings.isNotEmpty(error)) {
					if (!ul) {
						Attributes attrs = new Attributes();
						attrs.id(params)
							.cssStyle(params)
							.add("class", defs((String)params.get("cssClass"), getDefaultULClass()));
						stag("ul", attrs);

						attrsLI.add("class", getDefaultLIClass());

						ul = true;
					}

					// li for each error
					stag("li", attrsLI);

					// img for error
					write(icon(getDefaultIMGClass()));

					if (Attributes.isTrue(params.get("escape"), true)) {
						write(phtml(error));
					}
					else {
						write(error);
					}

					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 getDefaultULClass();

	/*
	 * default class for LI element
	 */
	protected abstract String getDefaultLIClass();

	/*
	 * default class for IMG element
	 */
	protected abstract String getDefaultIMGClass();
}
