package hibergui.hibernate;

import java.util.List;

import org.eclipse.swt.widgets.Composite;
import org.hibernate.Criteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;

import hibergui.Form;
import hibergui.assoc.M2OEdit_Combo;

public abstract class HibernateM2OEdit_Combo<T> extends M2OEdit_Combo<T> implements HibernateM2OEdit<T> {

	public HibernateM2OEdit_Combo(Form<?> form, Composite cptParent, int style, String prop, String name, String editProp) {
		super(form, cptParent, style, prop, name, editProp);
	}

    @SuppressWarnings("unchecked")
    @Override
    protected List<T> findAll() {
        return createCriteria().list();
    }

    @SuppressWarnings("unchecked")
	@Override
	protected List<T> findSuch() {
		return createCriteriaByExample().list();
	}

    protected Criteria createCriteria() {
    	return ((HibernateForm) form).getSession().createCriteria(persistentClass).addOrder(Order.asc(editProp));
    }
    
    protected Criteria createCriteriaByExample() {
    	Criteria crit = createCriteria();
    	T x = extract();
    	if (x != null)
    		crit.add(createExample(x));
    	return crit;
    }
	
//	public final Example createExample() {
//		return createExample(extract());
//	}
	
	public Example createExample(T sample) {
		return Example.create(sample).
//		excludeZeroes().
		ignoreCase().
		enableLike(MatchMode.START);
	}
}
