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

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

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

@SuppressWarnings("unchecked")
public class FieldErrorRenderer extends AbstractTemplateRenderer {
	public FieldErrorRenderer(TemplateRenderingContext context) {
		super(context);
	}

	public void render() throws IOException {
		Map<String, List<String>> errors = (Map<String, List<String>>)findValue("fieldErrors");
		List<String> fieldErrorFieldNames = (List<String>)params.get("errorFieldNames");

		if (fieldErrorFieldNames != null && !fieldErrorFieldNames.isEmpty()) {
			// wrapping ul
			Attributes attrs = new Attributes();
			attrs.add("class",
					defs((String)params.get("cssClass"), "errorMessage")).cssStyle(
					params);
			stag("ul", attrs);

			// iterate over field error names
			for (String fieldErrorFieldName : fieldErrorFieldNames) {
				List<String> fieldErrors = errors.get(fieldErrorFieldName);
				if (fieldErrors != null) {
					for (String fieldError : fieldErrors) {
						stag("li", null);
						stag("span", null);
						body(fieldError);
						etag("span");
						etag("li");
					}
				}
			}

			etag("ul");
		}
		else if (errors != null && !errors.isEmpty()) {
			// wrapping ul
			Attributes attrs = new Attributes();
			attrs.add("class",
					defs((String)params.get("cssClass"), "errorMessage")).cssStyle(
					params);
			stag("ul", attrs);

			for (Map.Entry<String, List<String>> errorEntry : errors.entrySet()) {
				for (String fieldError : errorEntry.getValue()) {
					stag("li", null);
					stag("span", null);
					body(fieldError, Attributes.isTrue(params.get("escape")));
					etag("span");
					etag("li");
				}
			}

			etag("ul");
		}
	}
}
