/**
 * 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 java.io.StringReader;
import java.sql.Clob;
import java.util.Iterator;
import java.util.List;

import javax.servlet.jsp.PageContext;

import org.apache.commons.io.IOUtils;
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 AbstractTextareaToHtmlDecorator implements ColumnDecorator, ColumnDecoratorHandler {
	protected PageContext pageContext = null;

    public AbstractTextareaToHtmlDecorator() {
        super();
    }

    public String decorate(Object value, String wrapTag, String rowWrapTag) {
    	return decorate(value, wrapTag, rowWrapTag, "\n");
    }

    public String decorate(Object value, String wrapTag, String rowWrapTag, String splitChar) {
    	if (value == null) {
    		return "";
    	}
    	try {
    		StringBuilder output = new StringBuilder("");
    		if (wrapTag != null) {
    			output.append("<").append(wrapTag).append(">");
    		}
    		String valueString = (value instanceof Clob)?IOUtils.toString(((Clob)value).getCharacterStream()):value.toString();
			String[] righe = valueString.split(splitChar);
			for (String riga : righe) {
	    		if (rowWrapTag != null) {
	    			output.append("<").append(rowWrapTag).append(">");
	    		}
				output.append(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();
		}
    }

	/**
	 * 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;
	}

}
