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

import java.beans.PropertyEditorSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.FlushMode;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.multipart.MultipartFile;

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

	private MultipartFile file;
	
	@Autowired @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
	
	public MultipartFile getFile() {
		return file;
	}

	public void setFile(MultipartFile file) {
		this.file = file;
	}

	/**
	 * 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 BlobEditor() {
	}

	@Override
	public void setValue(Object value) {
		file = (MultipartFile)value;
	}

	@Override
	public Object getValue() {
		try {
			if (file.getSize() == 0) {
				return null;
			}
			return Hibernate.getLobCreator(getSessionFactory().getCurrentSession()).createBlob(file.getInputStream(), file.getInputStream().available());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
