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.apache.lucene.index.IndexableField;
import org.hibernate.search.bridge.LuceneOptions;
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 {
			IndexableField clazz = document.getField("_hibernate_class");
			IndexableField 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);
		}
	}

	@Override
	public void set(String name, Object value, Document document, LuceneOptions luceneOptions) {
		// TODO Auto-generated method stub
		
	}
}
