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

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

import org.apache.commons.collections.CollectionUtils;
import org.apache.struts2.components.template.TemplateRenderingContext;

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

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

		Attributes attrsLI = new Attributes();
		attrsLI.add("class", "n-field-error");

		if (CollectionUtils.isEmpty(fieldErrorFieldNames)) {
			fieldErrorFieldNames = errors.keySet();
		}

		if (CollectionUtils.isNotEmpty(fieldErrorFieldNames)) {
			// iterate over field error names
			for (String fieldErrorFieldName : fieldErrorFieldNames) {
				List<String> fieldErrors = errors.get(fieldErrorFieldName);
				if (fieldErrors != null) {
					boolean ul = false;

					String label = null;
					if (Attributes.isTrue(params.get("label"))) {
						label = getText(fieldErrorFieldName)
							+ defs((String)params.get("labelseparator"), ":")
							+ ' ';
					}
					for (String fieldError : fieldErrors) {
						if (StringUtils.isNotEmpty(fieldError)) {
							if (!ul) {
								// wrapping ul
								Attributes attrs = new Attributes();
								attrs.add("errorFor", fieldErrorFieldName)
									.add("class", defs((String)params.get("cssClass"), "n-field-errors"))
									.cssStyle(params);
								stag("ul", attrs);

								ul = true;
							}
							stag("li", attrsLI);
							write(icon("n-icon n-icon-error n-field-error"));
							write(label);
							if (Attributes.isTrue(params.get("escape"), true)) {
								write(phtml(fieldError));
							}
							else {
								write(fieldError);
							}
							etag("li");
						}
					}
					if (ul) {
						etag("ul");
					}
				}
			}
		}
	}
}
