/**
 * Licensed under the MICE s.r.l.
 * End User License Agreement
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.micegroup.it/voila/license.html
 */
package it.mice.voila.runtime.displaytag.basedec;

import it.mice.voila.runtime.entity.Entity;

import java.util.Collection;

import javax.servlet.jsp.PageContext;

import org.apache.commons.lang.StringEscapeUtils;
import org.displaytag.decorator.ColumnDecorator;
import org.displaytag.decorator.ColumnDecoratorHandler;

/**
 * Display Column Decorator per la trasformazione delle date anche con l'ora.
 *
 */
public abstract class AbstractEntityListToHtmlListDecorator implements ColumnDecorator, ColumnDecoratorHandler {
	protected PageContext pageContext = null;

    public AbstractEntityListToHtmlListDecorator() {
        super();
    }

    public String decorate(Object value) {
    	return decorate(value, "ul", "li");
    }

    public String decorate(Object value, String wrapTag, String rowWrapTag) {
    	if (value == null) {
    		return "";
    	}
    	if (!(value instanceof Collection)) {
    		throw new RuntimeException("EntityListObjectTitleToHtmlListDecorator decorator must operate on an Entity collection");
    	}
    	Collection<Entity> entityList = null;
    	try {
    		entityList = (Collection<Entity>)value;
		} catch (Exception e1) {
    		throw new RuntimeException("EntityListObjectTitleToHtmlListDecorator decorator must operate on an Entity collection");
		}
    	
    	try {
    		StringBuilder output = new StringBuilder("");
    		if (wrapTag != null) {
    			output.append("<").append(wrapTag).append(">");
    		}
			for (Entity riga : entityList) {
	    		if (rowWrapTag != null) {
	    			output.append("<").append(rowWrapTag).append(">");
	    		}
				output.append(StringEscapeUtils.escapeXml(extractTextFromEntity(riga)));
	    		if (rowWrapTag != null) {
	    			output.append("</").append(rowWrapTag).append(">");
	    		}
			}
    		if (wrapTag != null) {
    			output.append("</").append(wrapTag).append(">");
    		}
			return output.toString();
		} catch (Exception e) {
			return value.toString();
		}
    }

	protected abstract String extractTextFromEntity(Entity riga);

	/**
	 * Called after the object has been retrieved from the bean contained in the list and
	 * before the decorate method will executed.
	 * 
	 * @param pageContext
	 *            Column instance object that allow you to surf the entire model of
	 *            displaytag
	 */
	public void setPageContext(PageContext pageContext) {
		this.pageContext = pageContext;
	}

}
