/*
 * 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.nxhtml;

import java.io.IOException;
import java.util.List;
import java.util.Map;

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

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

/**
 */
public class FieldWrapper extends NxhtmlTemplateRenderer {
	/**
	 * @param context context
	 */
	public FieldWrapper(TemplateRenderingContext context) {
		super(context);
	}

	protected void writeRequired() throws IOException {
		write("<span class=\"n-required\">");
		write(defs((String)params.get("requiredstring"), "*"));
		write("</span>");
	}

	protected void renderHeader() throws Exception {
		String name = (String)params.get("name");

		Map<String, List<String>> fieldErrors = (Map<String, List<String>>)findValue("fieldErrors");

		boolean hasFieldErrors = (name != null
			&& CollectionUtils.isNotEmpty(fieldErrors)
			&& fieldErrors.get(name) != null);

		Object required = params.get("required");
		String requiredposition = (String)params.get("requiredposition");
		
		String nxhtml_group = (String)findInContext("nxhtml_group");
		if (StringUtils.isEmpty(nxhtml_group)) {
			write("<tr class=\"n-tr-input\"><td class=\"n-td-label\">");

			String label = (String)params.get("label");
			if (StringUtils.isNotEmpty(label)) {
				Attributes al = new Attributes();
				al.addIfExists("for", params.get("id"))
				  .add("class", hasFieldErrors ? "n-label-error" : "n-label");
				stag("label", al);
				
				if (Attributes.isTrue(required)
						&& "left".equals(defs(requiredposition, "left"))) {
					writeRequired();
				}
	
				write(html(label));
	
				if (Attributes.isTrue(required)
						&& "right".equals(requiredposition)) {
					write("<span class=\"n-required\">*</span>");
				}
				write(defs((String)params.get("labelseparator"), ":"));
				etag("label");
			}
			etag("td");
			
			Attributes a = new Attributes();
			a.add("class", "n-td-input")
			 .addIfExists("align", params.get("align"));
			if (StringUtils.isEmpty((String)params.get("tooltip"))) {
				a.add("colspan", "2");
			}
			stag("td", a);
		}
		write((String)params.get("before"));
		
		String group = (String)params.get("group");
		if ("start".equals(group)) {
			putInContext("nxhtml_group", defs((String)params.get("name"), "-"));
		}
		else if (StringUtils.isNotEmpty(nxhtml_group)) {
			putInContext("nxhtml_group", nxhtml_group + "," + defs((String)params.get("name"), "-"));
		}
	}
	
	protected void renderFooter() throws Exception {
		Map<String, List<String>> fieldErrors = (Map<String, List<String>>)findValue("fieldErrors");

		Object required = params.get("required");
		String requiredposition = (String)params.get("requiredposition");
		
		String nxhtml_group = (String)findInContext("nxhtml_group");
		String group = (String)params.get("group");

        write((String)params.get("after"));

		if (StringUtils.isEmpty(nxhtml_group) || "end".equals(group)) {
			if (Attributes.isTrue(required)
					&& "side".equals(requiredposition)) {
				writeRequired();
			}
			
			if (CollectionUtils.isNotEmpty(fieldErrors)) {
				String[] fns;
				if (StringUtils.isEmpty(nxhtml_group)) {
					fns = new String[] { defs((String)params.get("name")) };
				}
				else {
					fns = StringUtils.split(nxhtml_group, ',');
				}
				
				for (String fn : fns) {
					List<String> fes = fieldErrors.get(fn);
					if (StringUtils.isNotEmpty(fn) && CollectionUtils.isNotEmpty(fes)) {
						boolean ul = false;
						for (String fe : fes) {
							if (StringUtils.isNotEmpty(fe)) {
								if (!ul) {
									Attributes aul = new Attributes();
									aul.add("errorFor", fn)
										.add("class", "n-field-errors");
									stag("ul", aul);
									ul = true;
								}
								write("<li class=\"n-field-error\">");
								write(icon("n-icon n-icon-error n-field-error"));
								write(phtml(fe));
								write("</li>");
							}
						}
						if (ul) {
							etag("ul");
						}
					}
				}
			}
			etag("td");

			String tooltip = (String)params.get("tooltip");
			if (StringUtils.isNotEmpty(tooltip)) {
				write("<td class=\"n-td-tooltip\">");
				write("<div class=\"n-tooltip\">");
				write(StringUtils.isEmpty(tooltip) ? "&nbsp;" : tooltip);
				write("</div>");
				etag("td");
			}

			etag("tr");
		}

		if ("end".equals(group)) {
			putInContext("nxhtml_group", "");
		}
	}
	
	public void render() throws Exception {
		renderHeader();
		renderSimple();
		renderFooter();
	}

}
