package it.mice.voila.runtime.hibernatesearch.annotation;

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

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.hibernate.search.bridge.TwoWayFieldBridge;

public class ObjectKeyBridge implements TwoWayFieldBridge {
	public ObjectKeyBridge() {
	}

	public String objectToString(Object object) {
		if (object instanceof EntityGeneric)
			return ((EntityGeneric)object).getObjectKey();
		return null;
	}

	public void set(String name, Object value, Document document, Store store,
			Index index, Float boost) {
		
		EntityGeneric id = (EntityGeneric) value;
        Field field = new Field(name, id.getObjectKey(), store, index);
        if (boost != null) {
            field.setBoost( boost );
        }
        document.add( field );
	}

	public Object get(String name, Document document) {
		try {
			Field clazz = document.getField("_hibernate_class");
			Field objectKey = document.getField("objectKey");
			Class entityClass = Class.forName(clazz.stringValue());
			EntityGeneric entity = (EntityGeneric)entityClass.newInstance();
			entity.setObjectKey(objectKey.stringValue());
			return entity;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
