package it.mice.voila.runtime.springmvc.editors;

import java.beans.PropertyEditorSupport;
import java.sql.Clob;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class ClobEditor extends PropertyEditorSupport {
	Log log = LogFactory.getLog(ClobEditor.class);

	private Clob content;
	
	@Autowired @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
	
	/**
	 * Create a new CustomDateEditor instance, using the given DateFormat
	 * for parsing and rendering.
	 * <p>The "allowEmpty" parameter states if an empty String should
	 * be allowed for parsing, i.e. get interpreted as null value.
	 * Otherwise, an IllegalArgumentException gets thrown in that case.
	 */
	public ClobEditor() {
	}

	/* (non-Javadoc)
	 * @see java.beans.PropertyEditorSupport#getAsText()
	 */
	@Override
	public String getAsText() {
		try {
			if (content == null) {
				return "";
			}
			//ByteArrayOutputStream output = new ByteArrayOutputStream();
			return IOUtils.toString(content.getCharacterStream());
			//StreamUtils.copy(content.getAsciiStream(), output);
			//return output.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/* (non-Javadoc)
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
	 */
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		try {
			if (text == null) {
				content = null;
			}
			content = Hibernate.getLobCreator(getSessionFactory().getCurrentSession()).createClob(text);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void setValue(Object value) {
		content = (Clob)value;
	}

	@Override
	public Object getValue() {
		return content;
	}

}
